Python Pandas Dataframe条件If、Elif、Els

2024-10-01 13:25:25 发布

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

在Python PandasDataFrame中,如果“searchterms”列包含来自联接的、管道分隔的列表的任何可能的字符串,我将尝试对行应用特定的标签。我怎么能用熊猫做条件if,elif,else语句呢?在

例如:

df = pd.DataFrame({'Search term': pd.Series(['awesomebrand inc', 'guy boots', 'ectoplasm'])})

brand_terms = ['awesomebrand', 'awesome brand']
footwear_terms = ['shoes', 'boots', 'sandals']

#Note: this does not work
if df['Search term'].str.contains('|'.join(brand_terms)):
  df['Label'] = 'Brand'
elif df['Search term'].str.contains('|'.join(footwear_terms)):
  df['Label'] = 'Footwear'
else:
  df['Label'] = '--'

期望输出示例:

^{pr2}$

我尝试过在contains()语句的末尾追加.any(),但它将Brand标签应用到每一行。在

我遇到的大多数例子都是比较列值==是否等于(不是我想要的)或者执行数值比较,而不是文本字符串比较。在


Tags: 字符串dfsearchif标签语句elselabel
1条回答
网友
1楼 · 发布于 2024-10-01 13:25:25

这里有一种方法,使用str.contains()np.where()

In [26]:
np.where(df['Search term'].str.contains('|'.join(brand_terms)),
        'Brand',
         np.where(df['Search term'].str.contains('|'.join(footwear_terms)),
             'Footwear',
             ' '))

Out[26]:
array(['Brand', 'Footwear', ' '],
      dtype='|S8')

您可以将其分配给df['Label'],就像

^{pr2}$

相关问题 更多 >