Pandas在多个列上对一个组进行滚动平均;大型数据帧

2024-03-29 05:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

-----+-----+-------------+-------------+-------------------------+
| ID1 | ID2 | Box1_weight | Box2_weight | Average Prev Weight ID1 |
+-----+-----+-------------+-------------+-------------------------+
|  19 | 677 |      3      |      2      |            -            |
+-----+-----+-------------+-------------+-------------------------+
| 677 |  19 |      1      |      0      |            2            |
+-----+-----+-------------+-------------+-------------------------+
|  19 | 677 |      3      |      1      |      (0 + 3 )/2=1.5     |
+-----+-----+-------------+-------------+-------------------------+
|  19 | 677 |      7      |      0      |       (3+0+3)/3=2       |
+-----+-----+-------------+-------------+-------------------------+
| 677 |  19 |      1      |      3      |      (0+1+1)/3=0.6      |

我想计算出过去3个箱子的移动平均重量,基于ID。我想对ID1中的所有ID都这样做。在

我已经把我想计算的列和计算一起放在上表中,标记为“Average Prev Weight ID1”


我可以用以下每列的平均值来计算每列的平均值:

^{pr2}$

然而,这并没有考虑到该物品也可能已包装在标有“Box2_weight”的列中

我怎样才能得到两列中每个ID的滚动平均值?在

欢迎任何指导。在


Tags: 数据标记id平均值averageid2weight重量
2条回答

不知道这是不是你想要的。我很难理解你的要求。但有一个办法:

ids = ['ID1', 'ID2']
ind = np.argsort(df[ids].to_numpy(), 1)

make_sort = lambda s, ind: np.take_along_axis(s, ind, axis=1)

f = make_sort(df[ids].to_numpy(), ind)
s = make_sort(df[['Box1_weight', 'Box2_weight']].to_numpy(), ind)

df2 = pd.DataFrame(np.concatenate([f,s], 1), columns=df.columns)

res1 = df2.groupby('ID1').Box1_weight.rolling(3, min_periods=1).mean().shift()
res2 = df2.groupby('ID2').Box2_weight.rolling(3, min_periods=1).mean().shift()

means = pd.concat([res1,res2], 1).rename(columns={'Box1_weight': 'w1', 'Box2_weight': 'w2'})
x = df.set_index([df.ID1.values, df.index])

final = x[ids].merge(means, left_index=True, right_index=True)[['w1','w2']].sum(1).sort_index(level=1)

df['final_weight'] = final.tolist()

^{pr2}$

这是我的尝试

堆叠2个id和2个weights列,以创建具有1个id和1个weight列的dataframe。计算运行平均值并将ID1的运行平均值分配回dataframe

我用过你的计算滚动平均数的代码,但是在做ti之前我把数据安排到了df2


import pandas as pd

d = {
    "ID1": [19,677,19,19,677],
    "ID2": [677, 19, 677,677, 19],
    "Box1_weight": [3,1,3,7,1],
    "Box2_weight": [2,0,1,0,3]
}

df = pd.DataFrame(d)
display(df)

period_length=3
ids = df[["ID1", "ID2"]].stack().values
weights = df[["Box1_weight", "Box2_weight"]].stack().values

df2=pd.DataFrame(dict(ids=ids, weights=weights))

rolling_avg = df2.groupby("ids")["weights"] \
    .apply(lambda x: x.shift().rolling(period_length, min_periods=1)
    .mean()).values.reshape(-1,2)

df["rolling_avg"] = rolling_avg[:,0]


display(df)

结果

^{pr2}$

相关问题 更多 >