Python 3.x 如何按索引和列比较字符串值,并在dataframe中应用and或逻辑?

Python 3.x 如何按索引和列比较字符串值,并在dataframe中应用and或逻辑?,python-3.x,pandas,if-statement,string-comparison,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 我希望按行和列比较字符串的值,并能够检查第1行中的两个值之一 我想创建以下逻辑: if df.col1.loc[[0]] =='Of course!' and (df.col1.loc[[1]]=='I love the service' or df.col1.l

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

   col1
0  ofcourse
1  I love the service
对于第1行,数据帧也可以具有此值:

   col1
0  ofcourse
1  I hate the service
我希望按行和列比较字符串的值,并能够检查第1行中的两个值之一

我想创建以下逻辑:

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]]
将返回
数据帧
,因为当您在此处执行条件时,这是
数据帧
,它将返回
数据帧
,这将引发错误

df.loc[0]
将返回
系列


更多信息

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

@RustyShackleford happy编码