使用np.where pandas 基于多个列的多个条件 [英] pandas multiple conditions based on multiple columns using np.where

查看:267
本文介绍了使用np.where pandas 基于多个列的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据两个条件为熊猫数据框的点着色.示例:

I am trying to color points of an pandas dataframe dependend on TWO conditions. Example:

如果col1的值> a(浮动)AND col2-的值,且col3的值< b(浮点),然后col 4的值=字符串,否则:其他字符串.

If value of col1 > a (float) AND value of col2- value of col3 < b (float), then value of col 4 = string, else: other string.

我现在已经尝试了许多不同的方法,而我在网上找到的所有内容仅取决于一种情况.

I have tried so many different ways now and everything I found online was only depending on one condition.

我的示例代码总是会引发错误: 系列的真值是模棱两可的.使用a.empty,a.bool(),a.item(),a.any()或a.all().

My example code always raises the Error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这是代码.尝试了几种变体而没有成功.

Here's the code. Tried several variations without success.

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')

顺便说一句:我明白,它说了什么,但没有怎么处理... 预先感谢!

Btw: I understand, what it says but not how to handle it... Thanks in advance!

推荐答案

选择条件使用布尔索引:

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

这篇关于使用np.where pandas 基于多个列的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆