【问题标题】:How to do Boolean filtering with two strings as conditions in pandas如何在熊猫中使用两个字符串作为条件进行布尔过滤
【发布时间】:2020-01-14 22:29:47
【问题描述】:

我正在尝试使用布尔过滤在 pandas 中创建一个新数据框,其中“job_id”列中的条目与“x”系列中的值匹配。

这是我尝试过的,虽然 |运算符不适用于字符串,所以我不确定该怎么做。

x = jobs[jobs['job_title'].isin(['Sales Representative', 'Sales Manager'])]['job_id']
employees['job_id'][(x[7]) | (x[8])]

【问题讨论】:

  • employees[employees['job_id'].isin(x.tolist())]?

标签: python pandas dataframe boolean


【解决方案1】:

如果没有可重现的示例,很难回答,但我认为问题只是改为:

employees['job_id'][ (employees['job_id'] == x[7]) | (employees['job_id'] == x[8]) ]

您的代码不包含任何布尔测试。这至少对我有用,下面的例子表明 |绝对可以与字符串一起使用:

df = pd.DataFrame({'num_legs': [2, 4, 8, 0],'letter': ['a', 'b', 'c', 'd'], 'num_specimen_seen': [10, 2, 1, 8]},index=['falcon', 'dog', 'spider', 'fish'])
df['num_specimen_seen'][(df['letter'] == 'a') | (df['letter'] == 'b')]
df['letter'][(df['letter'] == 'a') | (df['letter'] == 'b')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-22
    • 2018-09-10
    • 2021-09-21
    • 2020-03-22
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多