我有一個如下所示的資料集:
Value Type country mean
-1.975767 Weather Brazil
-0.540979 Fruits China
-2.359127 Fruits China
-2.815604 Corona China
-0.712323 Weather UK
-0.929755 Weather Brazil
我想計算型別和國家的所有不同組合的總體平均值。例如:
巴西天氣的平均值為 = (-1.975767 -0.929755) / 2
然后我想將這些組合添加到另一個表中:
df2 = pd.DataFrame()
country type mean count
Brazil Weather 2
Brazil Corona
China Corona 1
China Fruits 2
我可以這樣計算平均值:
print(df.groupby(["type", "country"])["value"].mean())
但是如何以所需格式將這些值保存在新的 df 中?
編輯:這有效
df_new = df.groupby(["type", "country"], as_index = False)["value"].mean()
但是如果我嘗試以相同的方式添加計數:
df_new = df.groupby(["type", "country"], as_index = False).count()
它轉置所有列而不是在平均列之后添加計數列
uj5u.com熱心網友回復:
您可以as_index在您的groupby:
df_new = df.groupby(["type", "country"], as_index = False)["value"].mean()
然后結果是一個標準的資料框:
type country value
0 Corona China -2.815604
1 Fruits China -1.450053
2 Weather Brazil -1.452761
3 Weather UK -0.712323
編輯:我們如何添加另一列count?您可以簡單地附加一個帶有新結果的新列,groupby如下所示:
# original answer
df_new = df.groupby(["type", "country"], as_index = False)["value"].mean().rename(columns={'value':'mean'})
# Add count also
df_new['count'] = df.groupby(["type", "country"])["value"].count().tolist()
df_new
輸出:
type country mean count
0 Corona China -2.815604 1
1 Fruits China -1.450053 2
2 Weather Brazil -1.452761 2
3 Weather UK -0.712323 1
uj5u.com熱心網友回復:
就個人而言,我更喜歡 JANO 的回答,但這是我想出的:
import pandas as pd
dataframe = pd.DataFrame({"Value":[-1.23, -1.65, -0.123, -0.67, 2.456], "Type":["Weather", "Fruits", "Corona", "Corona", "Weather"], "country": ["Brazil", "China", "China", "Iran", "Iran"]})
resultDataframe = {"Value":[], "Type":[], "country":[]}
for country in dataframe["country"].unique():
tempDataframe = dataframe[dataframe["country"] == country]
a = tempDataframe.groupby(by="Type").mean().reset_index()
for index, row in a.iterrows():
resultDataframe["Value"].append(row["Value"])
resultDataframe["Type"].append(row["Type"])
resultDataframe["country"].append(country)
pd.DataFrame(resultDataframe)
| 價值 | 型別 | 國家 | |
|---|---|---|---|
| 0 | -1.23 | 天氣 | 巴西 |
| 1 | -0.123 | 電暈 | 中國 |
| 2 | -1.65 | 水果 | 中國 |
| 3 | -0.67 | 電暈 | 伊朗 |
| 4 | 2.456 | 天氣 | 伊朗 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424153.html
上一篇:如何僅使用numpy屏蔽影像
