ranya
ranya

Reputation: 43

Length mismatch error for python groupby plot

I want to plot mean values of a certain column in a df1 after grouping them based on the weekday. The df1 is filtered from another df based on specific column values. The first data frame contains labor data for different plane types. I filter df1 for plane type and then plot the mean of the labor data on weekly basis.The following is the code:

df1 = df[df['Aircraft'].str.contains('SB_A330')]

weekday = df1['Labor_Hrs'].groupby(df1.index.dayofweek).mean()

weekday.index = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']

weekday.plot(style=['-'])

This code only works for certain categories, I get a length mismatch error for some of them. e.g. if there are Aircraft categories 'A','B','C' and 'D', it works for 'A' & 'B" for the other I get the following error:

"Length mismatch: Expected axis has 1 elements, new values have 7 elements" or

"Length mismatch: Expected axis has 3 elements, new values have 7 elements"

The graph I get is like this : plot for category A

Upvotes: 1

Views: 1133

Answers (1)

jezrael
jezrael

Reputation: 863741

You need reindex for adding missing days for Series with length 7:

weekday=df1['Labor_Hrs'].groupby(df1.index.dayofweek).mean().reindex(range(7), fill_value=0)

Sample:

rng = pd.date_range('2017-04-03', periods=6, freq='59H')
df1 = pd.DataFrame({'Labor_Hrs': range(6)}, index=rng)  
print (df1)
                     Labor_Hrs
2017-04-03 00:00:00          0
2017-04-05 11:00:00          1
2017-04-07 22:00:00          2
2017-04-10 09:00:00          3
2017-04-12 20:00:00          4
2017-04-15 07:00:00          5

weekday=df1['Labor_Hrs'].groupby(df1.index.dayofweek).mean().reindex(range(7), fill_value=0)
weekday.index = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']

print (weekday)
Mon      1.5
Tues     0.0 <-added 0 for missing 
Wed      2.5
Thurs    0.0 <-added 0 for missing 
Fri      2.0
Sat      5.0
Sun      0.0 <-added 0 for missing 
Name: Labor_Hrs, dtype: float64

Upvotes: 1

Related Questions