【问题标题】:Selecting dataframe rows by muliple conditions in pandas在熊猫中按多个条件选择数据框行
【发布时间】:2020-12-28 04:55:02
【问题描述】:

我可以根据某些条件从 pandas df 中选择行:

    cardio = df[df.indications == 'Cardiovascular / cardiology']
    end_aug = '2020-08-31'
    start_aug = '2020-08-01'

    mask = (df['date']>start_aug) & (df['date']<=end_aug)
    df = df.loc[mask,df['indications']]

但我还想使用“cardio”变量来缩小我在 ['indications'] 列中的选择范围,例如:

    df = df.loc[mask,df['indications']== 'Neoplasms / cancer / oncology']

但是上面的代码返回了一个错误:IndexingError: Unalignable boolean Series provided as indexer(boolean Series的索引和索引对象的索引不匹配)。

在我的情况下,如何使用“cardio”变量来使用面具和其他选择?

【问题讨论】:

  • df.loc[mask&amp;(df['indications']== 'Neoplasms / cancer / oncology')]?
  • @henry 谢谢。它返回一个空数据框,并且:FutureWarning: elementwise comparison failed;而是返回标量,但将来会执行元素比较
  • @henry 抱歉,它有效!我忘了一个括号。

标签: python pandas multipleselection


【解决方案1】:

另一种解决方案:

searchfor = ['Neoplasms', 'cancer', 'oncology']
df = df[df['indications'].str.contains('|'.join(searchfor))]

【讨论】:

  • 谢谢。 .contains 的搜索列表是否区分大小写?
  • 是的。最好全部改成小写:df.str.lower()
猜你喜欢
  • 1970-01-01
  • 2020-01-12
  • 2018-07-10
  • 1970-01-01
  • 2019-02-26
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
相关资源
最近更新 更多