Rob*_*ert 8 python numpy conditional-statements pandas
我试图在两个条件下对大熊猫数据帧的颜色进行着色.例:
如果col1的值> a(浮点)和col3的值 - col3的值<b(浮点数),则col 4的值= string,否则:其他字符串.
我现在尝试了很多不同的方法,我在网上找到的所有方法都只取决于一个条件.
我的示例代码总是引发错误:系列的真值是不明确的.使用a.empty,a.bool(),a.item(),a.any()或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')
Run Code Online (Sandbox Code Playgroud)
顺便说一句:我理解,它说的是什么,但不知道如何处理它...提前谢谢!
Ale*_*der 16
选择标准使用布尔索引:
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
Run Code Online (Sandbox Code Playgroud)
将IF包装在函数中并应用它:
def color(row):
borderE = 3.
ex = 0.
if (row.A > borderE) and( row.B - row.C < ex) :
return "somestring"
else:
return "otherstring"
df.loc[:, 'color'] = df.apply(color, axis = 1)
Run Code Online (Sandbox Code Playgroud)
产量:
A B C color
0 0 11 20 otherstring
1 1 12 19 otherstring
2 2 13 18 otherstring
3 3 14 17 otherstring
4 4 15 16 somestring
5 5 16 15 otherstring
6 6 17 14 otherstring
7 7 18 13 otherstring
8 8 19 12 otherstring
9 9 20 11 otherstring
Run Code Online (Sandbox Code Playgroud)