【问题标题】:Check if multiple strings are present in pandas dataframe检查熊猫数据框中是否存在多个字符串
【发布时间】:2018-01-28 12:14:18
【问题描述】:

我正在尝试确定是否在 dataframe 中找到了两个变量

table:
Code    index
600.SI  4th Q 2015
500.SI  Full Year
ggr.SI  1st Q 2016

# If variable_code and variable_date is not found in table, print not found
if table['Code'].str.contains(variable_code).any() & table['index'].str.contains(variable_date).any():
    print('found')
else:
    print('not found')

但是,它总是返回我found

我认为我的 if 语句的结构不正确,无法对两个项目进行 bool 比较。

如何解决?

更新

通常,variable_code 将在 table 中找到。如果在table 中找到variable_code,请检查variable_date 是否也存在。

我想要实现的是,如果这两个条件都不存在,请打印not found

【问题讨论】:

  • 抱歉,我不在,所以无法测试解决方案/响应。非常感谢您帮助回答,我很快就会给他们一个机会! :)

标签: python string pandas dataframe text


【解决方案1】:

& 替换为and& 是按位与运算符。

【讨论】:

  • 感谢丹尼尔如此迅速地回复。我已经尝试过了,但它仍然不起作用。它仍然打印found。补充一下,variable_code 通常会在table 中找到,但如果找到variable_code,则and variable_date 找不到,则打印not found。这就是我想要实现的目标
【解决方案2】:

默认使用str.containsregex=True,所以如果你不小心,你就不会匹配到正确的东西。如果您想检查是否相等而不是包含,请使用 == 运算符,如下所示:

if not table[(table['Code'] == variable_code) 
             & (table['index'] == variable_date)].empty: # https://stackoverflow.com/a/45780191/4909087
    print('Found')
else:
    print('Not found')

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 2018-09-05
    • 1970-01-01
    • 2014-06-26
    • 2018-07-01
    • 1970-01-01
    • 2021-01-16
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多