Skip to main content
 首页 » 编程设计

python之比较 Pandas 中的两列之错误 : The truth value of a Series is ambiguous

2024年10月24日9tintown

我有一个名为 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