我有一个数据帧,包含在特定分钟结束时的(股票)价格。在
DF列是:
import numpy.random as nprnd from pandas import DataFrame n = 10 # Number of samples # Starting at 8:00 AM, set some (n) random prices between 4-5 df = DataFrame({'minute_id': range(480,480+n), 'price':(5-4) * nprnd.random(n) + 4 }) df['change'] = df.price - df.price.shift(1) df['direction'] = df.change.map(lambda x: 0 if x == 0 else x/abs(x)) df = df.dropna() df
我想给这个数据框加几列。在
我可以通过一次迭代DF行来创建所有这些列。 但我确信还有一种更为(Python式的)方式来做这件事。在
我也不知道如何处理丢失的数据(如果我在分钟内有差距)
编辑:
在我想添加的4列中,1和4很容易。。。在
C4:这只是一个周期为4的滚动平均数
C1:滚动平均可以得到另一个最小周期的参数。在
将其设置为1并将窗口大小设置为df的长度,将为集合中的每一行提供一个运行平均值。在
df['rolling_avg'] = pd.rolling_mean(df.price, n, 1)
对于其他两个专栏,我仍在努力找到最好的方法。在
好吧,经过一番“闲逛”之后,我有了一个对我有用的东西。在
这也许可以用一种更“泛泛而谈”的方式来完成,但这是一种合理的方式来完成它。在
我要感谢安迪·海登、杰夫和菲利普·克劳德,感谢他们指出“给熊猫10分钟” 它没有包含直接的答案,但很有帮助。 还有,安迪·海登派我去创造滚动平均线,这对我有很大的帮助。在
所以让我们一列一列地去做
添加第1列:迄今为止的平均价格
添加第4列:最后4行的平均价格
在当前“blcok”(方向)中添加“change”列的col 2:CumSum()
添加第3列:当前“块”中的行号(方向)
完整代码:
输出:
相关问题 更多 >
编程相关推荐