简体   繁体   中英

Grouping and ordering columns in a Pandas dataframe

I have a Pandas dataframe with many columns, one of which is "movie title", I want to find the top 5 movie titles that appear in the most rows, and place them in descending order.

For example:

movie title

Title 1
Title 2
Title 2
Title 3
Title 3
Title 3

Should become:

movie title     count

Title 3         3
Title 2         2
Title 1         1

It can be in the same or a new dataframe. I may be missing a simple solution as I'm extremely new to Pandas. Thanks for your help!

try

df.groupby('movie title')['movie title'].aggregate(['count']).reset_index().sort('count', ascending=False)

or step by step

df = df.groupby('movie title')['movie title'].aggregate(['count'])
df = df.reset_index()
df = df.sort('count', ascending=False)

the '[ ]' inside the aggregate are important

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM