简体   繁体   English

select 行来自 pandas dataframe 在另一列不同的列中具有相同值并找到平均值并使其成为字典

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

相关问题 从 Pandas DataFrame 中选择一列中具有相同值但另一列中具有不同值的行 - Select rows from a Pandas DataFrame with same values in one column but different value in the other column 将 pandas dataframe 转换为具有一列键和另一列值的字典 - Convert pandas dataframe into dictionary with keys one column and values the other 如何将一列中的值传播到其他列中的行(熊猫数据框) - How to propagate values in one column to rows in other columns (pandas dataframe) Pandas - 创建新列,其中的值取自同一数据框中的其他行 - Pandas - Create new column where values are taken from other rows in the same dataframe 从 Pandas Dataframe 中选择一列中具有相同值而另一列仅缺失的行 - Selecting rows from Pandas Dataframe with same values in one column that have only missing in another 根据熊猫列中的字符串值从DataFrame中选择行 - Select rows from a DataFrame based on string values in a column in pandas 根据熊猫列中值的最后一个字符从DataFrame中选择行 - Select rows from a DataFrame based on last characters of values in a column in pandas 在 Pandas DataFrame 中查找具有相同索引的一列中的唯一值 - Find unique values in one column that have the same index in Pandas DataFrame Pandas DataFrame:根据不同行的值创建一列 - Pandas DataFrame : Create a column based on values from different rows Pandas数据框选择具有指定列中最高值的整个行 - Pandas dataframe select entire rows with highest values from a specified column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM