[英]Select rows from a Pandas DataFrame with same values in one column but different value in the other column
[英]select rows from pandas dataframe with same values in one column different on the other &find the average&make it a dictionary
假设我有一个 dataframe 像:
A B C D
1 2010 one 0 0
2 2020 one 2 4
3 2007 two 4 8
4 2010 one 8 4
5 2020 four 6 12
6 2007 three 7 14
7 2006 four 7 14
我想获得同一列 A 值的列 C 值,找到平均值并使其成为字典,以便我的 output 看起来像:
{ "2006": 14, "2007": 11,"2010":2 .....}
解决这个问题最实用的方法是什么? 我有大约 10,000 行,我将它们一一写下来没有任何意义。我希望我清楚地写下了我的问题。
使用groupby
+ mean
计算每个组的平均值,并to_dict
转换为字典:
df.groupby('A')['C'].mean().to_dict()
output: {2006: 7.0, 2007: 5.5, 2010: 4.0, 2020: 4.0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.