Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python order dataframe alphabetically

Tags:

python

pandas

I would like to reorder dataframe by student name. Does anybody have some suggestions?

df = pd.DataFrame({
        'student': [
            'monica', 'nathalia', 'anastasia', 'marina', 'ema'
        ],

    'grade' : ['excellent', 'excellent', 'good', 'very good', 'good'
    ]
    })

    print (df)

                student   grade

        0       monica    excellent        
        1       nathalia  excellent         
        2       anastasia good        
        3       marina    very good          
        4       ema       good 
like image 661
Sheron Avatar asked Apr 13 '17 21:04

Sheron


People also ask

How do you sort a DataFrame alphabetically in Python?

You can sort a dataframe using the sort_values method. Show activity on this post. df. sort_values(by=['contig', 'pos'], ascending=True) # where contig and pos are the column names.


2 Answers

Pre pandas 0.17:

# Sort by ascending student name
df.sort('student')
# reverse ascending
df.sort('student', ascending=False)

Pandas 0.17+ (as mentioned in the other answers):

# ascending
df.sort_values('student')
# reverse ascending
df.sort_values('student', ascending=False)
like image 149
sgrg Avatar answered Oct 01 '22 19:10

sgrg


You can sort a dataframe using the sort_values method.

df.sort_values('student')
like image 44
James Avatar answered Oct 01 '22 18:10

James