使用 np.where 基于多列的 pandas 多个条件

Posted

技术标签:

【中文标题】使用 np.where 基于多列的 pandas 多个条件【英文标题】:pandas multiple conditions based on multiple columns using np.where 【发布时间】:2016-08-04 19:43:20 【问题描述】:

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

如果 col1 的值 > a (float) AND col2 的值- col3 的值

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

我的示例代码总是引发错误: Series 的真值是模棱两可的。使用 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')

顺便说一句:我明白,它说的是什么,但不知道如何处理它...... 提前致谢!

【问题讨论】:

【参考方案1】:

选择标准使用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

【讨论】:

【参考方案2】:

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

产量:

  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

【讨论】:

where相比,这有多快/慢?【参考方案3】:

对我来说@Alexander 的解决方案在我的特定情况下不起作用,我必须使用列表来传递这两个条件,然后转置输出,我的解决方案也适用于这种情况:

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

产量:

    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 多个条件的主要内容,如果未能解决你的问题,请参考以下文章

Pandas 掩码 / where 方法与 NumPy np.where

在 np.where 条件下使用 pandas 可为空的整数 dtype

pandas比较两个dataframe特定数据列的数值是否相同并给出差值:使用np.where函数

Pandas:np.where 在数据帧上有多个条件

使用 np.where() 在 pandas 数据框中将 True/False 值更改为离散值

熊猫相当于 np.where