Python 最近的未来值不等于当前行
我有一个熊猫数据框,其中有一列,Python 最近的未来值不等于当前行,python,pandas,vectorization,Python,Pandas,Vectorization,我有一个熊猫数据框,其中有一列,price,还有一个DateTimeIndex。我想创建一个新列,当price下一次改变时,该列为1,如果它降低,则为0。多个连续行可能具有相同的price 例如: import pandas as pd df = pd.DataFrame({"price" : [10, 10, 20, 10, 30, 5]}, index=pd.date_range(start="2017-01-01", end="2017-01-06")) 然后,输出应为: 2017-01
price
,还有一个DateTimeIndex。我想创建一个新列,当price
下一次改变时,该列为1,如果它降低,则为0。多个连续行可能具有相同的price
例如:
import pandas as pd
df = pd.DataFrame({"price" : [10, 10, 20, 10, 30, 5]}, index=pd.date_range(start="2017-01-01", end="2017-01-06"))
然后,输出应为:
2017-01-01 1
2017-01-02 1
2017-01-03 0
2017-01-04 1
2017-01-05 0
2017-01-06 NaN
实际上,这个DF有大约20毫米的行,所以我正在寻找一种矢量化的方法来实现这一点。使用shift:
sh = df['price'].shift(-1)
out = sh[~sh.isnull()] = df['price']<=sh
sh=df['price'].shift(-1)
out=sh[~sh.isnull()]=df['price']使用移位:
sh = df['price'].shift(-1)
out = sh[~sh.isnull()] = df['price']<=sh
sh=df['price'].shift(-1)
out=sh[~sh.isnull()]=df['price']以下是一种方法:
计算差价并上移1
使用numpy.where
将一个分配给价格上涨的头寸,将零分配给价格下跌的头寸
回填指示器列,使无变化值与下一个可用观察值相同
代码:
import numpy as np
price_diff = df.price.diff().shift(-1)
df['indicator'] = np.where(price_diff.gt(0), 1, np.where(price_diff.lt(0), 0, np.nan))
df['indicator'] = df.indicator.bfill()
df
# price indicator
#2017-01-01 10 1.0
#2017-01-02 10 1.0
#2017-01-03 20 0.0
#2017-01-04 10 1.0
#2017-01-05 30 0.0
#2017-01-06 5 NaN
有一种方法可以做到这一点:
计算差价并上移1
使用numpy.where
将一个分配给价格上涨的头寸,将零分配给价格下跌的头寸
回填指示器列,使无变化值与下一个可用观察值相同
代码:
import numpy as np
price_diff = df.price.diff().shift(-1)
df['indicator'] = np.where(price_diff.gt(0), 1, np.where(price_diff.lt(0), 0, np.nan))
df['indicator'] = df.indicator.bfill()
df
# price indicator
#2017-01-01 10 1.0
#2017-01-02 10 1.0
#2017-01-03 20 0.0
#2017-01-04 10 1.0
#2017-01-05 30 0.0
#2017-01-06 5 NaN