简体   繁体   中英

Pandas group by - sort and plot

I have a grouped data frame:

a = [1, 2, 3, 4]  + [11, 22, 33, 44]  + [111, 222, 333, 444] + [1111, 2222, 3333, 4444] + [1111, 2222, 3333, 4444]+ [11111, 22222, 33333, 44444]+ [111111, 222222, 333333, 444444]
b = ['Friday', 'Friday', 'Friday', 'Friday', 
    'Monday', 'Monday', 'Monday', 'Monday',
     'Saturday', 'Saturday', 'Saturday', 'Saturday',
     'Sunday', 'Sunday', 'Sunday', 'Sunday',
     'Thursday','Thursday','Thursday','Thursday',
     'Tuesday','Tuesday','Tuesday','Tuesday',
     'Wednesday', 'Wednesday', 'Wednesday', 'Wednesday'] 
df = pd.DataFrame(data=[a,b]).T

How to plot this data frame using bar plot that on x axis will be day of week and on y axis values? How to sort this data frame by day of week from Monday to Sunday?

First lets do a bit cleanup. Rename the columns to something more readable:

df = df.rename(columns = {1: 'day', 0:'value'})

Next I'll manually define the order. If you want Sunday as 1st just change the order:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

Apply Categorical function and then sort the values.

df['Date'] = pd.Categorical(df['day'], categories=days, ordered=True)
df = df.sort_values('Date')

Now we can apply the standart pandas plot:

df =df.set_index('Date')
df.plot.bar()

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