BioFluorescent277
BioFluorescent277

Reputation: 127

How to specifically sort a DataFrame by reordering rows [Python]

I am trying to change the order of this dataframe:

    genre       average_voteM
7   Documentary 7.200000
11  Film-Noir   6.606486
4   Biography   6.551788
12  History     6.476688
23  War         6.383735
3   Animation   6.274451
8   Drama       6.159555
14  Music       6.143162
15  Musical     6.124792
17  News        6.000000

so that the genres are in this order:

7   Documentary 7.200000
11  Film-Noir   6.606486
4   Biography   6.551788
12  History     6.476688
23  War         6.383735
17  News        6.000000
3   Animation   6.274451
15  Musical     6.124792
14  Music       6.143162
8   Drama       6.159555

The data is IMDB film data from here. I have tried the method A[[7,8]] = A[[8,7]], however this did not work for me.

Any help would be greatly appreciated :)

Upvotes: 0

Views: 32

Answers (2)

Chris
Chris

Reputation: 16162

sort_order = {
    'Documentary':0,
    'Film-Noir':1,
    'Biography':2,
    'History':3,
    'War':4,
    'News':5,
    'Animation':6,
    'Musical':7,
    'Music':8,
    'Drama':9
}

df.sort_values(by=['genre'], key=lambda x: x.map(sort_order))

Upvotes: 1

wasif
wasif

Reputation: 15488

You can filter rows using df.loc:

df.loc[2:len(df),'average_voteM'] = df.loc[2:len(df),'average_voteM'].sort_values()

Replace 2 with the start row

Upvotes: 0

Related Questions