gpt4 book ai didi

python-3.x - 如何使用 Pandas 在 Python 中对字典中的数据进行排序

转载 作者:行者123 更新时间:2023-12-03 11:17:32 25 4
gpt4 key购买 nike

我正在尝试按 Perpetrator's Age 递增顺序对我的输出进行排序。目前,它是完全无序的。

我曾尝试使用排序功能,但它不起作用。

    xl = pd.ExcelFile('Murders.xlsx')
df = xl.parse('Sheet1')
age = df['Perpetrator Age']

freq1 = collections.Counter(df['Perpetrator Age'])
freq = [{'Perpetrator_Age': m, 'Freq': f} for m, f in freq1.items()]
file = open("MurderPerpAge.js", "w+")
file.write(json.dumps(freq))
file.close()

我希望我的输出按年龄从最小到最大排序。
[{"Perpetrator_Age": 15, "Freq": 5441}, {"Perpetrator_Age": 17, "Freq": 14196},...

最佳答案

选项 1:纯 python

试试 sorted带 key :

sorted(freq , key=lambda x: x["Perpetrator_Age"])

选项 2:混合 Pandas 和纯 python
freq1 = Counter(df['Perpetrator Age'].sort_values())
freq = [{'Perpetrator_Age': m, 'Freq':f} for m,f in freq1.items()]

选项 3:纯 Pandas

灵感来自 WeNYoBen 的回答。
freq1 = df.groupby('Perpetrator Age').size()
freq1.name = 'Freq'
freq = freq1.reset_index().to_dict('r')

关于python-3.x - 如何使用 Pandas 在 Python 中对字典中的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com