简体   繁体   English

使用 Pandas.query() 方法过滤数据?

[英]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.我想过滤所有ticket_id都有“其他”的product_type,并用语音替换“其他”。

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. ERROR:root: Series 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 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)

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:您可以通过以下方式检查product_type中是否存在“其他”:

if 'others' in df.product_type.tolist():
    #there is 'others' in product_type
else:
    #there is no 'others' in product_type
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM