我有一个DataFrame,它包含(股票的)在特定分钟结束时的价格。
DF列是:
从熊猫进口numpy.random n= 10 #样品数#从上午8:00开始,设定4-5 df = DataFrame({'minute_id':range(480,480+n),‘DataFrame’:(5-4)* nprnd.random(n) +4 }) df‘’change‘= df.price - df.price.shift(1) df’方向‘= df.change.map(lambda x: 0 if x == 0 of x/abs(x)) df= df.dropna() df()
我想向这个DF添加几个列。
我可以通过一次迭代DF行来创建所有这些列。但我相信还有一种更多的方法来做这件事。
我也不知道如何处理丢失的数据(如果我在minute_id中有空白)
编辑:
在我想增加的4列中,1和4很容易.
C4:这只是一个周期为4的滚动平均值
C1:滚动均值可以得到最小周期的另一个参数。
将其设置为1并将窗口大小设置为df的长度将为集合中的每一行提供运行平均值。
df‘_avg’= pd.rolling_mean(df.price,n,1)
对于其他两列,我仍在努力寻找获得它的最佳方法。
发布于 2013-08-25 05:42:42
好吧,在“玩”了很多之后,我找到了一些对我有用的东西。
这可能是一种更多的“疯狂”的方式,但这是一个合理的方式来完成它。
我想感谢安迪海登,杰夫和菲利普克劳德指出,"10分钟到熊猫“,它没有直接的答案,但非常有帮助。此外,安迪海登派我创造滚动的均值,这对我很大程度上是一个方向。
因此,让我们逐列执行,
全文代码:
import numpy.random as nprnd
from pandas import DataFrame
import pandas as pd
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()
#------------------------------------------
# Col 1, rolling Avg over the entire DF
df['rolling_avg'] = pd.rolling_mean(df.price, n, 1)
#------------------------------------------
# Col 4, rolling Avg windows size of 4
df['RA_wnd_4'] = pd.rolling_mean(df.price, 4, 1)
#------------------------------------------
# Helper code for cols 2, 3
# Adding Helper column that shows when direction have been changed
df['dir_change'] = (df.direction.shift(1) != df.direction).astype(int)
# Identify the DF "blocks" for every direction change
df['block'] = df.dir_change.cumsum()
# Split the DF based on those bolcks
grouped = df.groupby('block')
# Add Function that will cumsum() for a block, and call it
def f1(group):
return DataFrame({'rolling_count' : group.cumsum()})
df['one'] = 1
#------------------------------------------
# Col 2, CumSum() of the 'change' column while in the current "blcok" (direction)
df['rolling_count'] = grouped.change.apply(f1)
#------------------------------------------
# Col 3, Count in the current "block" (Direction)
df['rolling_count'] = grouped.one.apply(f1)
df = df.drop('one', axis=1)
print df输出:
minute_id price change direction rolling_avg RA_wnd_4 dir_change block rolling_count
1 481 4.771701 0.474349 1 4.771701 4.771701 1 1 1
2 482 4.300078 -0.471623 -1 4.535889 4.535889 1 2 1
3 483 4.946744 0.646666 1 4.672841 4.672841 1 3 1
4 484 4.529403 -0.417340 -1 4.636981 4.636981 1 4 1
5 485 4.434598 -0.094805 -1 4.596505 4.552706 0 4 2
6 486 4.171169 -0.263429 -1 4.525616 4.520479 0 4 3
7 487 4.416980 0.245810 1 4.510096 4.388038 1 5 1
8 488 4.727078 0.310098 1 4.537219 4.437456 0 5 2
9 489 4.049097 -0.677981 -1 4.482983 4.341081 1 6 1https://stackoverflow.com/questions/18400955
复制相似问题