[英]select rows from pandas dataframe with same values in one column different on the other &find the average&make it a dictionary
Let's say i have a dataframe like:假设我有一个 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
And i want to get colum C values of the same column A values, find the average and make it a dictionary so that my output would look like:我想获得同一列 A 值的列 C 值,找到平均值并使其成为字典,以便我的 output 看起来像:
{ "2006": 14, "2007": 11,"2010":2 .....}
What is the most practical way to solve this?解决这个问题最实用的方法是什么? I have about 10,000 rows and it doesn't make any sense of me to write them down one by one.I hope I clearly wrote about my problem.
我有大约 10,000 行,我将它们一一写下来没有任何意义。我希望我清楚地写下了我的问题。
Use groupby
+ mean
to compute the mean per group and to_dict
to convert to dictionary:使用
groupby
+ mean
计算每个组的平均值,并to_dict
转换为字典:
df.groupby('A')['C'].mean().to_dict()
output: {2006: 7.0, 2007: 5.5, 2010: 4.0, 2020: 4.0}
output:
{2006: 7.0, 2007: 5.5, 2010: 4.0, 2020: 4.0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.