elksie5000
elksie5000

Reputation: 7772

How to manually arrange rows in pandas dataframe

I have a small dataframe produced from value_counts() that I want to plot with a categorical x axis. It s a bit bigger than this but:

Age  Income
25-30 10
65-70 5
35-40 2

I want to be able to manually reorder the rows. How do I do this?

Upvotes: 0

Views: 913

Answers (2)

ManojK
ManojK

Reputation: 1640

From here Link, you can create a sorting criteria and use that:

df = pd.DataFrame({'Age':['25-30','65-70','35-40'],'Income':[10,5,2]})
sort_criteria = {'25-30': 0, '35-40': 1, '65-70': 2}
df = df.loc[df['Age'].map(sort_criteria).sort_values(ascending = True).index]

Upvotes: 1

ignoring_gravity
ignoring_gravity

Reputation: 10531

You can reorder rows with .reindex:

>>> df                                                                                                                                                                                             
   a  b
0  1  4
1  2  5
2  3  6

>>> df.reindex([1, 2, 0])                                                                                                                                                                          
   a  b
1  2  5
2  3  6
0  1  4

Upvotes: 4

Related Questions