【问题标题】:np.where() or another boolean way for new pandas dataframe columnnp.where() 或新熊猫数据框列的另一种布尔方式
【发布时间】:2017-03-03 00:17:37
【问题描述】:

我想在数据框中创建一个列,其中包含以另一个计算的布尔值为条件的股票价格。

              close    high   low
    Index
      0        10       11     10
      1        11       12     10
      2        10       11      9

首先我想定义一些在逻辑上看起来像但实际上很长的条件:

 condition1: if df.close > df.close.shift() return True

实际上,我想定义更多条件,这些条件都提供真或假。然后我将它包含在 np.where() 中:

 df['NewColumn'] = np.where(condition1() == True, 'A', 'B')

我试图将条件定义为一个函数,但未能正确设置它。我想避免将条件的内容直接写入 np.where() ,因为它会因为多个嵌套条件而变得过于复杂。

那么,我怎样才能最有效地完成我的任务呢?

编辑:一个函数可能看起来像这样(但它在上面的 np.where() 中不起作用):

def condition1(): 
    if df.Close > df.Close.shift(1):
        return True
    Else
        return False

【问题讨论】:

  • numpy.where(df.close > df.close.shift(), 'A', 'B') 应该可以工作
  • 愿意分享您尝试将其定义为函数但未能正确设置的情况
  • @Paul H,由于实际条件的复杂性和数量,我想避免将条件直接写入公式
  • @Abdou 我添加了一个我想象的设置示例

标签: python pandas numpy


【解决方案1】:

更新: IMO 你不需要“条件”作为函数:

In [89]: cond1 = df.Close > df.Close.shift(1)

In [90]: cond2 = df.High < 12

In [91]: df['New_Close'] = np.where(cond1, 'A', 'B')

In [92]: df
Out[92]:
   Close  High  Low New_Close
0     10    11   10         B
1     11    12   10         A
2     10    11    9         B

In [93]: df['New_High'] = np.where(cond1, '<12', '>=12')

In [94]: df
Out[94]:
   Close  High  Low New_Close New_High
0     10    11   10         B     >=12
1     11    12   10         A      <12
2     10    11    9         B     >=12

旧答案:

我并没有真正看到这种方法的任何优势(好处),但你可以这样做:

def condition1(): 
    return (df.Close > df.Close.shift(1))

def condition2(): 
    return (df.High < 12)


In [72]: df['New_Close'] = np.where(condition1(), 'A', 'B')

In [73]: df
Out[73]:
   Close  High  Low New_Close
0     10    11   10         B
1     11    12   10         A
2     10    11    9         B

In [74]: df['New_High'] = np.where(condition2(), '<12', '>=12')

In [75]: df
Out[75]:
   Close  High  Low New_Close New_High
0     10    11   10         B      <12
1     11    12   10         A     >=12
2     10    11    9         B      <12

PS IMO 直接像@PaulH said in his comment 那样做会更容易更好

【讨论】:

  • 谢谢,这似乎有效。好处主要是光学性质的。当 np.where() 变长和嵌套时,应该提高它的可读性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2022-01-16
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多