[英]Pandas closest future value not equal to current row
我有一个Pandas DataFrame,其中有一个列, price
和一个DateTimeIndex。 我想创建一个新列,当price
下次更改时增加时为1,如果price
降低则为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具有约20mm的行,因此我确实在寻找一种矢量化的方法。
这是执行此操作的一种方法:
计算价格差并向上移动一位;
使用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
df['New']=(df-df.shift(-1))[:-1].le(0).astype(int)
df
Out[879]:
price New
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
使用班次:
sh = df['price'].shift(-1)
out = sh[~sh.isnull()] = df['price']<=sh
要么
sh = df['price'].shift(-1)
out = np.where(sh.isnull(), np.nan, df['price']<=sh)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.