Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering data with Pandas.query() method?

I want to filter product_type which is having "others" for all ticket_id and replace "others" with voice.

Sample dataframe

ticket_id  network  product_type

123        AAA      tv
345        AAA      others       
567        BBB      others
678        CCC      others
789        DDD      broad

Expected output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ticket_id  network  product_type

123        AAA      tv
345        AAA      voice       
567        BBB      voice
678        CCC      voice
789        DDD      broad

I tried the below function but it gives an error:

ERROR:root:The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

def product_mapping(df):
    try:
        data = df.query('product_type == "others"')['ticket_id']
        if data:
            data["product_type"] = data["product_type"].replace({"others": "voice"})
            return data
        else:
            return df
    except Exception as error:
        logger.error(error)

>Solution :

try this:

df['product_type'] = df.product_type.str.replace('others', 'voice')

Output:

ticket_id   network product_type
0   123 AAA tv
1   345 AAA voice
2   567 BBB voice
3   678 CCC voice
4   789 DDD broad

You can check if ‘others’ exist in product_type by:

if 'others' in df.product_type.tolist():
    #there is 'others' in product_type
else:
    #there is no 'others' in product_type
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading