python-3.x - 如何按索引和列比较字符串值并在数据框中应用 AND OR 逻辑?

标签 python-3.x pandas if-statement string-comparison

我有一个如下所示的数据框:

   col1
0  ofcourse
1  I love the service

数据框的第 1 行也可以具有此值:

   col1
0  ofcourse
1  I hate the service

我想按行和列比较字符串的值,并能够检查 row1 中的两个值之一。

我想创建这个逻辑:

if df.col1.loc[[0]] =='Of course!' and (df.col1.loc[[1]]=='I love the service' or df.col1.loc[[1]]=='I hate the service'):
    print('good')

当我运行上面的逻辑时,出现错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我做错了什么?

最佳答案

您应该删除[]

df.col1.loc[0] =='Of course!' and (df.col1.loc[1]=='I love the service' or df.col1.loc[1]=='I hate the service')

为什么会发生:

df.loc[[0]] 将返回 DataFrame,因为当您在此处执行条件时,它是 DataFrame,因此它将返回DataFrame,这将引发错误

df.loc[0] 将返回 Series


更多信息

type(df.loc[[0]])
<class 'pandas.core.frame.DataFrame'>
type(df.loc[0])
<class 'pandas.core.series.Series'>

关于python-3.x - 如何按索引和列比较字符串值并在数据框中应用 AND OR 逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840548/

相关文章:

c++ - 如何用 if 语句替换预处理器宏?

java - 总计未加起来

python - 从嵌套字典到 CSV 文件

python - 不一致的理解语法?

python - 使用 pd.to_datetime 时出错

c - 编程查找元音,If 语句未分配正确的值

python - 在多个类和多个模块中使用全局变量

python - 如何让机器人加入语音 channel discord.py

python - Pandas:使用 bool 掩码替换多列的值

python - 将间隔日期时间值转换为任意频率时间序列