Pandas 分组并找出最大值和最小值之间的差异

问题描述 投票:0回答:3

我有一个数据框。我汇总如下。但是,我想将它们区分为最大值 - 最小值

enter image description here

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

期望:

enter image description here

python pandas numpy
3个回答
11
投票

您可以使用

np.ptp
,这会为您进行
max - min
计算:

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

或者,

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

如果您将系列作为输出。


5
投票

比较一下两者:

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

@cs95的答案是正确的做法,而且也有更好的时机! :

设置:

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)

%%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)

3
投票

您应该对表的列执行基本的逐元素操作,您可以这样做:


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

© www.soinside.com 2019 - 2024. All rights reserved.