Reputation: 83
I am trying to sort my output by Perpetrator's Age in increasing order. At the moment, it is completely unordered.
I have tried to use the sort function but it does not work.
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()
I expect my output to be ordered by the age from youngest to oldest.
[{"Perpetrator_Age": 15, "Freq": 5441}, {"Perpetrator_Age": 17, "Freq": 14196},...
Upvotes: 4
Views: 74
Reputation: 150745
Try sorted
with key:
sorted(freq , key=lambda x: x["Perpetrator_Age"])
freq1 = Counter(df['Perpetrator Age'].sort_values())
freq = [{'Perpetrator_Age': m, 'Freq':f} for m,f in freq1.items()]
Inspired by WeNYoBen's answer.
freq1 = df.groupby('Perpetrator Age').size()
freq1.name = 'Freq'
freq = freq1.reset_index().to_dict('r')
Upvotes: 3
Reputation: 323266
Since you mentioned pandas
, I am using value_counts
, since the default is sort by freq
df['Perpetrator Age'].value_counts().reset_index().to_dict('r')
Upvotes: 2