这里有一个例子:
# Generate some random time series dataframe with 'price' and 'volume'
x = pd.date_range('2017-01-01', periods=100, freq='1min')
df_x = pd.DataFrame({'price': np.random.randint(50, 100, size=x.shape), 'vol': np.random.randint(1000, 2000, size=x.shape)}, index=x)
df_x.head(10)
price vol
2017-01-01 00:00:00 56 1544
2017-01-01 00:01:00 70 1680
2017-01-01 00:02:00 92 1853
2017-01-01 00:03:00 94 1039
2017-01-01 00:04:00 81 1180
2017-01-01 00:05:00 70 1443
2017-01-01 00:06:00 56 1621
2017-01-01 00:07:00 68 1093
2017-01-01 00:08:00 59 1684
2017-01-01 00:09:00 86 1591
# Here is some example aggregate function:
df_x.resample('5Min').agg({'price': 'mean', 'vol': 'sum'}).head()
price vol
2017-01-01 00:00:00 78.6 7296
2017-01-01 00:05:00 67.8 7432
2017-01-01 00:10:00 76.0 9017
2017-01-01 00:15:00 74.0 6989
2017-01-01 00:20:00 64.4 8078
然而,如果我想要提取依赖于多个列的其他聚合信息,我该怎么办?
例如,我想在此处添加2列,分别称为all_up
和all_down
。
这2列的计算定义如下:
每5分钟内,1分钟采样价格和成交量下跌的次数,称为all_down
列,在此期间它们上涨的次数称为all_up
列。
以下是我期望看到的2列:
price vol all_up all_down
2017-01-01 00:00:00 78.6 7296 2 0
2017-01-01 00:05:00 67.8 7432 0 0
2017-01-01 00:10:00 76.0 9017 1 0
2017-01-01 00:15:00 74.0 6989 1 1
2017-01-01 00:20:00 64.4 8078 0 2
这个功能依赖于2列。但在Resampler对象的agg函数中,它似乎只接受3种类型的函数:
- 一个字符串或分别应用于每个列的函数。
- 一个分别应用于每个列的函数列表。
- 一个键匹配列名的字典。仍然只将值作为函数应用于单个列。
所有这些功能似乎都不符合我的需求。
all_up
列计算每5分钟内1分钟价格上涨且交易量也上涨的次数。all_down
则相反。 - StayFoolishprice
和vol
数据是随机整数,这可能是我们得到不同值的原因?实际上,我只手动计算了前10分钟的all_up
和all_down
。 - StayFoolish