【问题标题】:pandas multiple conditions based on multiple columns using np.where使用 np.where 基于多列的 pandas 多个条件
【发布时间】: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')

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

【问题讨论】:

    标签: python numpy pandas conditional-statements


    【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2017-02-02
        • 2021-10-19
        • 2020-04-29
        • 2022-06-13
        • 1970-01-01
        • 2021-07-20
        • 2017-11-18
        • 1970-01-01
        • 2020-04-02
        相关资源
        最近更新 更多