Pandas groupby and find difference between max and min

Viewed 1985

I have a dataframe. I have aggregated as below. But, I want to difference them as max value - min values

enter image description here

dnm=df.groupby('Type').agg({'Vehicle_Age': ['max','min']})

Expect:

enter image description here

3 Answers

You can use np.ptp, this does the max - min calculation for you:

df.groupby('Type').agg({'Vehicle_Age': np.ptp})

Or,

df.groupby('Type')['Vehicle_Age'].agg(np.ptp) 

If you a Series as the output.

just compare the two :

grouping = df.groupby('Type')
dnm = grouping.max() - grouping.min()

@cs95's answer is the right approach and also has better timing! :

setup:

df = pd.DataFrame({'a':np.arange(100),'Type':[1 if i %2 ==0 else 0 for i in range(100)]})

@cs95:

%timeit df.groupby('Type').agg({'a': np.ptp}) 

1.29 ms ± 39.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

vs

%%timeit  
grouping = df.groupby('Type') 
dnm = grouping.max() - grouping.min() 

1.57 ms ± 299 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

You should perform a basic element-wise operation on the columns of the table which you can do like so:


import pandas as pd

# This is just setup to replicate your example
df = pd.DataFrame([[14, 7], [15, .25], [14, 9], [13, 2], [14, 4]], index=['Large SUV', 'Mid-size', 'Minivan', 'Small', 'Small SUV'], columns = ['max', 'min'])

print(df)

#             max   min
# Large SUV   14  7.00
# Mid-size    15  0.25
# Minivan     14  9.00
# Small       13  2.00
# Small SUV   14  4.00

# This is the operation that will give you the values you want
diff = df['max'] - df['min']

print(diff)

# Large SUV     7.00
# Mid-size     14.75
# Minivan       5.00
# Small        11.00
# Small SUV    10.00

Related