Pandas histogram grouped by several attributes

obchardon :

I have a dataframe that contains the number of passengers at each stop, for each bus trip and for each day.

I would like to plot an histogram that show us the number of passengers for all the different combinations of [trip_id, day] sorted by departure time.

The minimal example below produce the expected result:

import pandas as pd
import random

# Dummy dataframe where:
# day = day of operation
# line = bus line number
# trip = the trip ID
# dep_time = departure time
# stop_name = the stop name
# load = number of passenger at each stop
d = {'day': ['Fri'] * 6 + ['Sat'] * 6 + ['Fri'] * 6 + ['Sat'] * 6,
     'line': [1] * 12 + [2] * 12,
     'trip': [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
     'dep_time': list(range(1, 7)) * 4,
     'stop_name': ['George Street', 'Casino', 'Beauregard'] * 4 + ['Virginia Street', 'Monbenont', 'Baker street'] * 4,
     'load': [random.randint(1, 10) for x in range(24)]}
df = pd.DataFrame(data=d)

# Get the unique day and trip ID
uday = df['day'].unique().tolist()
utrip = df['trip'].unique().tolist()

# For each group of distinct [day,trip] plot an histogram of the number of passenger at each stop
# and sort the stop by departure time.
for day in uday:
    for trip in utrip:
        # Filter the dataframe for each unique day, trip ID and direction.
        df_to_plot = df.sort_values('dep_time')[(df['day'] == day) & (df['trip'] == trip)]
        if not df_to_plot.empty:
            title = 'line: ' + str(df_to_plot['line'].unique()[0]) \
                    + ', ' \
                    + 'trip_id: ' + str(trip) \
                    + ' ' \
                    + day

            ax = df_to_plot.plot.bar(x='stop_name', y='load', rot=90, title=title)

This code produce 8 histograms but I've to create a loop for each group. Is there a way to produce the same results by using some kind of group_by function with pandas ?

Quang Hoang :

IIUC, yes, this could be done with groupby:

for (d,t), v in df.sort_values('dep_time').groupby(['day','trip']):
    # your other plot commands here:
    if len(v):
        v.plot.bar(x='stop_name',y='load')

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407934&siteId=1