df['increasing'] = (df['Open'].diff() > 0).astype(int)
或
df['increasing'] = (df['Open'] - df['Open'].shift() > 0).astype(int)
两者都有效,但前者更快。
举个例子,
In [41]: import pandas_datareader.data as pdata
In [42]: df = pdata.get_data_yahoo('AAPL', start='2009-01-02', end='2009-12-31')
In [43]: df.head()
Out[43]:
Open High Low Close Volume Adj Close
Date
2009-01-02 85.880003 91.040001 85.160000 90.750001 186503800 11.933430
2009-01-05 93.170003 96.179998 92.709999 94.580002 295402100 12.437067
2009-01-06 95.950000 97.170001 92.389998 93.020000 322327600 12.231930
2009-01-07 91.809999 92.500001 90.260003 91.010000 188262200 11.967619
2009-01-08 90.430000 93.150002 90.039998 92.699999 168375200 12.189851
diff() 返回相邻行之间的差异:
In [45]: df['Open'].diff().head()
Out[45]:
Date
2009-01-02 NaN
2009-01-05 7.290000
2009-01-06 2.779997
2009-01-07 -4.140001
2009-01-08 -1.379999
Name: Open, dtype: float64
(df['Open'].diff() > 0) 返回一个布尔值系列,当差值为正时为 True:
In [46]: (df['Open'].diff() > 0).head()
Out[46]:
Date
2009-01-02 False
2009-01-05 True
2009-01-06 True
2009-01-07 False
2009-01-08 False
Name: Open, dtype: bool
调用 .astype(int) 会将 False 转换为 0,将 True 转换为 1:
In [47]: (df['Open'].diff() > 0).astype('int').head()
Out[47]:
Date
2009-01-02 0
2009-01-05 1
2009-01-06 1
2009-01-07 0
2009-01-08 0
Name: Open, dtype: int64
如果你需要赋值,代码会变得有点复杂
第三个可能的值,2,当差值为 0 时:
import numpy as np
diff = df['Open'].diff()
conditions = [diff > 0, diff < 0]
choices = [1, 0]
df['increasing'] = np.select(conditions, choices, default=2)
np.select 是np.where 的泛化。 np.where 适合处理 1 个条件,np.select 处理多个条件。上面的条件是diff > 0和diff < 0,我们希望分别赋值1和0:
conditions = [diff > 0, diff < 0]
choices = [1, 0]
当两个条件都不为真时,np.select 分配默认值 2:
df['increasing'] = np.select(conditions, choices, default=2)