首页 > 解决方案 > Python pandas - 对列值求和并创建字典

问题描述

我期望将 Pandas Dataframe 的输出相加并返回为按降序排序的列表。

示例:df 具有以下值

         a      b        c 
------------------------------
0        3      5        0
1        0      1        2
2        1      2        1     

df.sum(axis = 1, skipna = True) 将对列求和并返回为

a = 4
b = 8
c = 3

我希望结果为 [b, a, c]。如何获取列表?

标签: pythonpandas

解决方案


在使用pandas.Series.tolistpandas.Series.to_dict转换为列表或字典后,您可以使用pandas.Series.sort_values对输出 Serie 进行排序:

my_sum_serie=df.sum().sort_values(ascending=False) #get a ordered pandas Series
print(my_sum_serie)
my_list=my_sum_serie.tolist() #get a list
print(my_list)
my_dict=my_sum_serie.to_dict() #get a dict
print(my_dict)


b    8
a    4
c    3
dtype: int64
[8, 4, 3]
{'b': 8, 'a': 4, 'c': 3}

推荐阅读