从列中得到低、高和平均值

2024-05-12 20:36:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从一个专栏中找出低、高、中的意思。但是,我只想按列值进行聚合。例如,如果有两行具有相同的列值,则将这两行聚合在一起。而且,它们必须是同一个载体。像这样:

处理前:

carrier   class   price
SP        A       22
VZ        C       33
XM        A       50 
XM        D       20     
SP        A       88
VZ        C       100

处理后:

carrier   class   price   low   high   mean
SP        A       22      22    88     55
VZ        C       33      33    100    66.5
XM        A       50      50    50     50
XM        D       20      20    20     20
SP        A       88      22    88     55
VZ        C       100     33    100    66.5

如你所见,如果我们有相同的载体和相同的类别,那么我们聚合得到低、高和平均值。如果我们有相同的载体,但没有相同的类别,那么我们就不加总,但我们仍然得到低,高,平均值,这是相同的数字作为类的价格。你知道吗

我希望结果和处理后的结果一模一样。结果应该是一个数据帧。我怎样才能做到这一点?你知道吗


Tags: 数字mean类别pricespclasslow平均值
1条回答
网友
1楼 · 发布于 2024-05-12 20:36:45

^{}与元组列表一起用于具有聚合函数的新列名,将^{}与原始DataFrame一起使用:

d = [('low','min'),('high','max'),('mean','mean')]
df1 = df.join(df.groupby(['carrier','class'])['price'].agg(d), on=['carrier','class'])
print (df1)
  carrier class  price  low  high  mean
0      SP     A     22   22    88  55.0
1      VZ     C     33   33   100  66.5
2      XM     A     50   50    50  50.0
3      XM     D     20   20    20  20.0
4      SP     A     88   22    88  55.0
5      VZ     C    100   33   100  66.5

细节:

print (df.groupby(['carrier','class'])['price'].agg(d))
               low  high  mean
carrier class                 
SP      A       22    88  55.0
VZ      C       33   100  66.5
XM      A       50    50  50.0
        D       20    20  20.0

或者使用^{},有趣的解决方案:

d = [('low','min'),('high','max'),('mean','mean')]
g = df.groupby(['carrier','class'])['price']
for i, j in d:
    df[i] = g.transform(j)
print (df)
  carrier class  price  low  high  mean
0      SP     A     22   22    88  55.0
1      VZ     C     33   33   100  66.5
2      XM     A     50   50    50  50.0
3      XM     D     20   20    20  20.0
4      SP     A     88   22    88  55.0
5      VZ     C    100   33   100  66.5

相关问题 更多 >