【问题标题】:Python Pandas Dataframe Conditional If, Elif, ElsePython Pandas 数据框条件 If、Elif、Else
【发布时间】:2015-06-05 01:03:38
【问题描述】:

在 Python Pandas DataFrame 中,如果“搜索词”列包含来自以竖线分隔的连接列表中的任何可能字符串,我会尝试将特定标签应用于行。如何使用 Pandas 执行条件 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'] = '--'

所需输出示例:

Search Term          Label
awesomebrand inc     Brand
guy boots            Footwear
ectoplasm            --

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

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

【问题讨论】:

  • .str.contains()?不需要.str 部分

标签: python if-statement pandas dataframe


【解决方案1】:

这是一种方法,使用 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']点赞

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

In [28]: df
Out[28]:
        Search term     Label
0  awesomebrand inc     Brand
1         guy boots  Footwear
2         ectoplasm        --

【讨论】:

  • 不错!这对我来自 Excel 和嵌套 If 语句的世界很有意义。非常感谢。
  • 如何在不抛出 SettingWithCopyWarning 的情况下执行相同的任务?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2017-05-03
  • 2017-07-03
  • 2014-03-09
  • 2021-03-07
  • 2020-07-30
相关资源
最近更新 更多