如何比较索引和列的字符串值并在数据帧中应用AND OR逻辑?

问题描述 投票:2回答:1

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

   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().

我究竟做错了什么?

python-3.x pandas if-statement string-comparison
1个回答
2
投票

你应该删除[]

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'>
© www.soinside.com 2019 - 2024. All rights reserved.