我有一个名为 m 的数据框,它包含三列 a
、b
、c
。我想将 b
列与 a
、c
进行比较,并将值放入 d
列中。
a b c 1 5 7 2 7 8 3 1 9 4 8 6
But when I try this in the following code, I got the error as
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
Code:
if m['b'] < m['a']:
m['d'] = m['a']
elif m['d'] > m['c']:
m['d'] = m['c']
else:
m['d'] = m['b']
m
有办法做到这一点吗?
最佳答案
您可以使用双 numpy.where
:
m['d'] = np.where(m['b'] < m['a'], m['a'], np.where(m['b'] > m['c'], m['c'], m['b']) )
print m
a b c d
0 1 5 7 5
1 2 7 8 7
2 3 1 9 3
3 4 8 6 6
关于python - 比较 pandas 中的两列 - 错误 : The truth value of a Series is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924588/