[英]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.