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

标签 python if-statement pandas dataframe series

我有一个名为 m 的数据框,它包含三列 abc。我想将 b 列与 ac 进行比较,并将值放入 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/

相关文章:

MySql: "IF"公式的结构是什么?请举例

Python - 多个循环中的方差分析测试

python - 如何根据 Pandas 中的另一列聚合一列

python - 多图片背景matplotlib

c++ - 为什么 if 语句不起作用

python - 使用 docker-compose 时调试链接的 docker 容器

python - Pandas 根据条件移动列数据

python - 使用 aggfunc 时出现 pandas InvalidIndexError

python - 如何使用 python 2.5 打包和解包数据

OSX 上的 python -m SimpleHttpServer [端口]