我有一個DataFrame,它有三列表示一個組,一組時間和一個值。我想計算每個組內的滾動方式,標準偏差等。現在我定義一個函數並使用apply。但是,對於非常大的數據集,這是非常緩慢的。以下是功能。加速分組熊貓數據框中滾動平均值/標準差的計算
def GetRollingMetrics(x, cols, windows, suffix):
for col in cols:
for win in windows:
x[col + '_' + str(win) + 'D' + '_mean' + '_' + suffix] = x.shift(1).rolling(win)[col].mean()
x[col + '_' + str(win) + 'D' + '_std' + '_' + suffix] = x.shift(1).rolling(win)[col].std()
x[col + '_' + str(win) + 'D' + '_min' + '_' + suffix] = x.shift(1).rolling(win)[col].min()
x[col + '_' + str(win) + 'D' + '_max' + '_' + suffix] = x.shift(1).rolling(win)[col].max()
return x
然後應用它,作爲一個例子,我用:
df = pd.DataFrame(np.random.randint(0,100,size=(1000000, 3)), columns=['Group','Time','Value'])
df.sort_values(by='Time', inplace=True)
df = df.groupby('Group').apply(lambda x: GetRollingMetrics(x, ['Value'], [7,14,28], 'my_suffix'))
有沒有更「Pandaic」或有效的方式做到這一點?
「Pandaic」... :-)另外,你想爲每列和每個窗口計算這些滾動狀態? –
那麼,在這個例子中,我只有一個'Value'列,但是我可能想要爲多列和多個窗口大小計算它,因此cols是一個列表。 – user1566200
和'Pandaic'確實聽起來更好 - 編輯:) – user1566200