treatyoself
treatyoself

Reputation: 83

How to order data in a dictionary in Python using Pandas

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

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150745

Option 1: Pure python

Try sorted with key:

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

Option 2: Mixed Pandas and pure python

freq1 = Counter(df['Perpetrator Age'].sort_values())
freq = [{'Perpetrator_Age': m, 'Freq':f} for m,f in freq1.items()]

Option 3: Pure Pandas

Inspired by WeNYoBen's answer.

freq1 = df.groupby('Perpetrator Age').size()
freq1.name = 'Freq'
freq = freq1.reset_index().to_dict('r')

Upvotes: 3

BENY
BENY

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

Related Questions