基于不同列的部分字符串匹配在新数据框列中创建标签

2024-06-28 20:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我已经看了很多关于这个问题的线索,似乎没有一个在makecase中起作用。 Creating a new column based on if-elif-else condition似乎是最接近我想要做的。你知道吗

在我的df中,我有一列产品名称。我试图创建一个函数,在该列的每一行中查找部分字符串匹配项,并基于该匹配项为新df列中的每一行创建一个标签。我想使用一个函数,因为我需要匹配大约5到6个模式。你知道吗

我使用contains()函数查找部分产品标题匹配。这将返回一个bool,然后在函数中使用else/if进行检查:

def label_sub_cat():
    if data['product'].str.contains('Proceedings', case=False) is True:
        return 'Proceedings'
    elif data['product'].str.contains('DVD', case=False) is True:
        return 'DVD'
    else:
        return 'Other'

data['product_sub_cat'] = data.apply(label_sub_cat(), axis=1)

我不断得到以下错误:

AttributeError: 'DataFrame' object has no attribute 'other'

Tags: 函数falsedfdatareturnifproductelse
2条回答

只要改变你的功能

def label_sub_cat(row):
    if row.product.str.contains('Proceedings', case=False) is True:
        return 'Proceedings'
    elif row.product.str.contains('DVD', case=False) is True:
        return 'DVD'
    else:
        return 'Other'

data['product_sub_cat'] = data.apply(label_sub_cat, axis=1)

中的函数数据框应用()应适用于数据框的每一行,而不是整个数据框。你知道吗

In [37]: df = pd.DataFrame({'product':['aProcedings', 'aDVD','vcd']})
In [38]: def label_sub_cat(row):
...:     if 'Procedings' in row['product']:
...:         return 'Proceedings'
...:     elif 'DVD' in row['product']:
...:         return 'DVD'
...:     else:
...:         return 'Other'
...:
...:

In [39]: df['product_sub_cat'] = df.apply(label_sub_cat, axis=1)

In [40]: df
Out[40]:
       product product_sub_cat
0  aProcedings     Proceedings
1         aDVD             DVD
2          vcd           Other

相关问题 更多 >