gpt4 book ai didi

python - 基于多列的 Pandas 多个条件

转载 作者:太空狗 更新时间:2023-10-29 20:36:29 27 4
gpt4 key购买 nike

我正在尝试根据两个条件为 Pandas 数据框的点着色。示例:

IF value of col1 > a AND value of col2 - value of col3 < b THEN value of col4 = string
ELSE value of col4 = other string.

我现在已经尝试了很多不同的方法,但我在网上找到的所有内容都只取决于一个条件。

我的示例代码总是引发错误:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这是代码。尝试了多种变体但均未成功。

df = pd.DataFrame()

df['A'] = range(10)
df['B'] = range(11,21,1)
df['C'] = range(20,10,-1)

borderE = 3.
ex = 0.

#print df

df['color'] = np.where(all([df.A < borderE, df.B - df.C < ex]), 'r', 'b')

顺便说一句:我明白,它说的是什么,但不知道如何处理。

最佳答案

选择标准使用Boolean indexing :

df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b')

>>> df
A B C color
0 0 11 20 r
1 1 12 19 r
2 2 13 18 r
3 3 14 17 b
4 4 15 16 b
5 5 16 15 b
6 6 17 14 b
7 7 18 13 b
8 8 19 12 b
9 9 20 11 b

关于python - 基于多列的 Pandas 多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603018/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com