熊猫:将滚动统计与原始数据集连接在一起



我想为我的数据帧添加滚动最大值、最小值和平均值。 我的数据集大约有 200 万行,因此使用 Apply 需要花费大量时间。这段代码将让我以非常有效的方式滚动,但是,我的问题是如何将这些连接到原始数据集。 df 是按对象分组的,out 是数据帧。我希望能够做这样的事情:out = pd.concat([df, d1, d2, d3, d4], 1)

import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(1000, 3)), 
columns=['Group','Time','Value'])
df.sort_values(by='Time', inplace=True)
suffix = 'my_suffix'
windows = [7, 14, 28]
df = df.groupby('Group')
d1 = pd.concat([df.rolling(w).mean()
.rename(columns=lambda x: x + '_' + str(w) + 'D_mean_' + suffix)
for w in windows] , 1)
d2 = pd.concat([df.rolling(w).std()
.rename(columns=lambda x: x + '_' + str(w) + 'D_std_' + suffix) 
for w in windows] , 1)
d3 = pd.concat([df.rolling(w).min()
.rename(columns=lambda x: x + '_' + str(w) + 'D_min_' + suffix) 
for w in windows] , 1)
d4 = pd.concat([df.rolling(w).max()
.rename(columns=lambda x: x + '_' + str(w) + 'D_max_' + suffix) 
for w in windows] , 1)
out = pd.concat([d1, d2, d3, d4], 1)

谢谢

你可以做

ori=df.copy()
pd.concat([ori.set_index('Group',append=True).swaplevel(0,1),out], 1).reset_index()

最新更新