5

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 3

9

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.

2
  • 2
    thats a better solution and also faster then maie.. %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) Dec 20, 2020 at 11:44
  • @adirabargil Thank you for timing, please add it to your answer and I will be happy to vote on it
    – cs95
    Dec 20, 2020 at 11:46
4

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)
1
  • 1
    Might also be worth including your setup to create Large Df so others can compare notes on timings.
    – cs95
    Dec 20, 2020 at 11:50
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.