python - 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]。如何获取列表?
解决方案
在使用pandas.Series.tolist或pandas.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}
推荐阅读
- angular - Moment Js时区功能不更改日期
- swift - 在 SwiftUI 中使用`@Binding` 初始化`@State`ful 结构
- android - 填充 RecyclerView 后,底部工作表对话框跳起来
- python-3.x - 为什么python3 for循环不覆盖变量?
- go - 不同类型的Golang接口——传值时的混乱
- perforce - Helix core 获取文件夹版本(带内容)
- python - python - setup.py sdist bdist_wheel
- json - 如何将我的 JSON 图像设置为 url 格式?
- angular - Angular 8:无法访问在 FileReader onloadend 方法中设置的类变量
- f#-data - F# - 使用 HtmlProvider 加载最后一行为空的表时出错