【问题标题】:Numpy Where with more than 2 conditionsNumpy Where 有两个以上的条件
【发布时间】:2018-12-20 10:04:28
【问题描述】:

早安,

我有以下数据框,其中包含两列整数和一个系列(差异),计算方式为:

diff = (df["col_1"] - df["col_2"]) / (df["col_2"])

我想创建数据框的一列,其值为:

  • 等于 0,如果 (diff >= 0) & (diff
  • 等于 1,如果 (diff > 0.35)

  • 等于 2,如果 (diff = - 0.35)

  • 等于 3,如果 (diff

我试过了:

df["Class"] = np.where( (diff >= 0) &  (diff <= 0.35), 0, 
np.where( (diff > 0.35), 1, 
np.where( (diff  < 0) & (diff >=  - 0.35) ), 2, 
np.where( ((diff <  - 0.35), 3) ))) 

但是报如下错误:

SystemError: <built-in function where> returned a result with an error set          

我该如何解决?

【问题讨论】:

    标签: python pandas numpy dataframe series


    【解决方案1】:

    您可以使用numpy.select分别指定条件和值。

    s = (df['col_1'] / df['col_2']) - 1
    
    conditions = [s.between(0, 0.35), s > 0.35, s.between(-0.35, 0), s < -0.35]
    values = [0, 1, 2, 3]
    
    df['Class'] = np.select(conditions, values, np.nan)
    

    【讨论】:

      【解决方案2】:

      也可以直接使用numpy.searchsorted:

      diff_classes = [-0.35,0,0.35]
      def getClass(x):
          return len(diff_classes)-np.searchsorted(diff_classes,x)
      
      df["class"]=diff.apply(getClass)
      

      searchsorted 将为您提供xdiff_classes 列表中的索引,然后您从 3 中减去该索引以获得所需的结果。

      编辑:可读性差一点,但它也可以在一行中工作:

      df["class"] = diff.apply(lambda x: 3-np.searchsorted([-0.35,0,0.35],x))

      【讨论】:

        猜你喜欢
        • 2013-04-26
        • 2021-04-08
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-16
        相关资源
        最近更新 更多