這是我的大型面板資料集:
| 日期 | x1 | x2 | x3 |
|---|---|---|---|
| 2017-07-20 | 50 | 60 | 凱文 |
| 2017-07-21 | 51 | 80 | 凱文 |
| 2016-05-23 | 100 | 200 | 凱茜 |
| 2016-04-20 | 20 | 20 | 凱茜 |
| 2019-01-02 | 50 | 60 | 獅子座 |
該資料集包含數十億行。我想做的是,我想計算 x1 和 x2 的 1 天差異百分比:將 t 和 t 1 表示為代表今天和明天的時間。我想計算(x1_{t 1} - x2_t) / x2_t
首先,我在寫作方面使用了最快的方式:
我創建了一個嵌套串列,其中包含每組的所有目標值x3:
nested_list = []
flatten_list = []
for group in df.x3.unique():
df_ = df[df.x3 == group]
nested_list.append((df_.x1.shift(-1) / df_.x2) / df_.x2))
for lst in nested_list:
for i in lst:
flatten_list.append(i)
df["target"] = flatten_list
但是,這種方法實際上需要一年的時間才能運行,這是不可實作的。
我還嘗試了原生 pandasgroupby方法以獲得潛在的可運行結果,但它似乎不起作用:
def target_calculation(x):
target = (x.x1.shift(-1) - x.x2) / x.x2
return target
df["target"] = df.groupby("x3")[["x1", "x2"]].apply(target_calculation)
我如何在不使用 for 回圈或可能矢量化整個程序的情況下計算這個?
uj5u.com熱心網友回復:
您可以groupby shift"x1" 并從中減去 "x2":
df['target'] = (df.groupby('x3')['x1'].shift(-1) - df['x2']) / df['x2']
輸出:
Date x1 x2 x3 target
0 2017-07-20 50 60 Kevin -0.15
1 2017-07-21 51 80 Kevin NaN
2 2016-05-23 100 200 Cathy -0.90
3 2016-04-20 20 20 Cathy NaN
4 2019-01-02 50 60 Leo NaN
注意
(df.groupby('x3')['x1'].shift(-1) / df['x2']) / df['x2']
產生相當于flatten_list但我不認為這是你真正想要的輸出,而是一個錯字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441286.html
標籤:Python 熊猫 数据框 熊猫-groupby
