熊猫 df 错误 - "The truth value of a Series is ambiguous." in if else 循环



我有一个pandas df,列,列,称为 group ,由三个值组成,分别为1,2和3。

如果其他语句,我正在尝试执行以下操作:

if df.group == 1:
   (code here)
elif df.group ==2:
   (code here)
else:
   (code here)

当我尝试运行我的话时,它会丢下以下错误: valueerror:系列的真实价值是模棱两可的。使用A.Empty,A.Bool(),A.Item(),A.Any()或a.all()。

我是否需要在数据框架上使用np。

您可以这样迭代:

for idx, val in enumerate(df.itertuples()):
    if df.loc[idx, 'group'] == 1:
       print('1')
    elif df.loc[idx, 'group'] ==2:
       print('2')
    else:
       print('3')

使用np.where请参阅此处

在您的情况下,df.group是"组"列中该系列的呼吁,例如:

df = pd.DataFrame({'group':[1,2,3,1,3,3,3,2,1,1]})
df.group
Out[42]: 
0    1
1    2
2    3
3    1
4    3
5    3
6    3
7    2
8    1
9    1
Name: group, dtype: int64

因此,将一系列[1,2,3,1 ... ]与单数值进行比较是没有意义的。这就是错误试图告诉您的。

听起来您正在尝试检索集合{1,2,3}中每个值的列索引。

在这种情况下使用:

[i for i,j in enumerate(df.group) if j == 1]
Out[48]: [0, 3, 8, 9]

相关内容

最新更新