假設我有多個資料框,其格式為
| 證件號碼 | 一種 | 乙 |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 3 | 5 |
| 2 | 5 | 6 |
| 1 | 6 | 7 |
我想按“Id”對資料框進行分組并應用攻擊,然后將新值存盤在不同的資料框中,例如
df_calc = pd.DataFrame(columns=["Mean", "Median", "Std"])
for df in dataframes:
mean = df.groupby(["Id"]).mean()
median = df.groupby(["Id"]).median()
std = df.groupby(["Id"]).std()
df_f = pd.DataFrame(
{"Mean": [mean], "Median": [median], "Std": [std]})
df_calc = pd.concat([df_calc, df_f])
這是我的最終資料框df_calc出現的格式

但我希望它看起來像這樣

我該怎么做呢?
uj5u.com熱心網友回復:
您可以嘗試agg多個功能,然后交換列級別并重新排序列:
out = df.groupby('Id no').agg({'A': ['median','std','mean'],
'B': ['median','std','mean']})
print(out)
A B
median std mean median std mean
Id no
1 4.0 2.828427 4.0 4.0 4.242641 4.0
2 4.0 1.414214 4.0 5.5 0.707107 5.5
out = out.swaplevel(0, 1, 1).sort_index(axis=1)
print(out)
mean median std
A B A B A B
Id no
1 4.0 4.0 4.0 4.0 2.828427 4.242641
2 4.0 5.5 4.0 5.5 1.414214 0.707107
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461477.html
