groupby based on one column and get the sum values in another column

Viewed 36

I have a data frame such

mode    travel time 
transit_walk    284.0   
transit_walk    284.0   
pt              270.0   
transit_walk    346.0   
walk            455.0   

I want to group by "mode" and get the sum of all travel time. so my desire result looks like:

mode           total travel time
transit_ walk   1200000000
pt               30000000
walk             88888888   

I have written the code such as

df.groupby('mode')['travel time'].sum()

however, I have the result such as:

mode
pt              270.01488.01518.01788.01300.01589.01021.01684....
transit_walk    284.0284.0346.0142.0142.01882.0154.0154.0336.0...
walk            455.018.0281.0554.0256.0256.0244.0244.0244.045...
Name: travel time, dtype: object

which just put all the time side by side, and it didn't sum them up.

1 Answers

There are strings in column travel time, so try use Series.astype:

df['travel time'] = df['travel time'].astype(float)

If failed bcause some not numeric value, use to_numeric with errors='coerce':

df['travel time'] = pd.to_numeric(df['travel time'], errors='coerce')

And last aggregate:

df1 = df.groupby('mode', as_index=False)['travel time'].sum()
Related