【发布时间】:2018-06-12 13:54:14
【问题描述】:
我已经四处搜索并有自己的解决方案,但我相信有更好的方法来实现结果。
我有一个包含以下列的数据框:
from_country to_country score
from_country 和 to_country 列具有相同的条目集,例如美国、英国、中国等。对于从到到的每种组合,都有一个特定的分数。
我需要计算每个国家/地区的平均得分,无论出现在 from_country 或 to_country 字段中。
df_from = df[["from_country", "score"]].copy()
df_from.rename(columns={"from_country":"country"}, inplace=True)
df_to = df[["to_country", "score"]].copy()
df_to.rename(columns={"to_country":"country"}, inplace=True)
df_countries = pd.concat([df_from, df_to])
然后最终计算新数据帧的平均值。
有没有更好的方法?
谢谢
【问题讨论】:
标签: python pandas dataframe group-by average