Comparing two columns in pandas - error: The truth value of a Series is ambiguous
Comparing two columns in pandas - error: The truth value of a Series is ambiguous
我有一个名为 m 的数据框,它包含三列 a
、b
、c
。我想将 b
列与 a
、c
列进行比较,并将值放入 d
列。
a b c
1 5 7
2 7 8
3 1 9
4 8 6
但是当我在下面的代码中尝试这个时,我得到了
的错误
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
代码:
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
我有一个名为 m 的数据框,它包含三列 a
、b
、c
。我想将 b
列与 a
、c
列进行比较,并将值放入 d
列。
a b c 1 5 7 2 7 8 3 1 9 4 8 6
但是当我在下面的代码中尝试这个时,我得到了
的错误The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
代码:
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