1

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

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)
3
  • df.query('product_type == "others"')? Commented Jul 22, 2022 at 8:16
  • @Timus Yup, I tried with this, but it's giving another error. Please refer my updated code above. Commented Jul 22, 2022 at 8:21
  • I think you wanna filter the ticket_id if the product_type is other Commented Jul 22, 2022 at 8:32

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks much! Can we get this through a function? if it is product with "others" then return voice else it should get the dataframe.
@bdfrd I have one doubt, why are you converting to list ? Any specific reason. I tried without tolist(), but if statement is not working.
No. That works but it returns false because it chevks whether “others” exist in indexes.
0
def mapping(df):
    try:
        if 'others' in df.product.tolist():
            df["product"] = df["product"].replace(['others'],'voice')  
            return df
        else:
            return df
        
    except Exception as error:
        logger.error(error)

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.