开发者社区> 问答> 正文

如何使用平均分组列添加行

我有一个像下面这样的数据框。 每个水果加一行,其中 我知道如何生成一个新列来显示每个水果的平均价格,但我不知道如何用这个平均值添加一行。 你能帮我吗?

import numpy as np
import pandas as pd
fruit = ['apple','apple','banana','banana','kiwi','kiwi','grape','grape']
ftype = ['one','two','one','two','three','one','one','two']
resource = ['us','us','us','us','us','us','us','us']
price = [100,150,200,300,120,300,400,500]
df = pd.DataFrame({'fruit':fruit,'ftype':ftype,'resource':resource,'price':price})
print(df)

原始dataframe:


    fruit  ftype  price resource
0   apple    one    100       us
1   apple    two    150       us
2  banana    one    200       us
3  banana    two    300       us
4    kiwi  three    120       us
5    kiwi    one    300       us
6   grape    one    400       us
7   grape    two    500       us

我想产生:

    fruit  ftype  price resource
0   apple    one    100       us
1   apple    two    150       us
    apple    avg    125      all
2  banana    one    200       us
3  banana    two    300       us
   banana    avg    250       all
4    kiwi  three    120       us
5    kiwi    one    300       us
     kiwi    avg    210       all
6   grape    one    400       us
7   grape    two    500       us
    grape    avg    450       all

问题来源StackOverflow 地址:/questions/59386739/pandas-how-to-add-rows-with-average-grouped-columns

展开
收起
kun坤 2019-12-25 21:52:24 401 0
1 条回答
写回答
取消 提交回答
  • 您可以使用datafame .assign来聚合平均值并添加新列。

    df1 = df.groupby('fruit', as_index=False)['price'].mean().assign(resource='all',ftype='avg')
    

    然后使用concat和排序值:

    df = (pd.concat([df, df1], sort=True)
            .sort_values(['fruit','resource'], ascending=[True, False])
            .reset_index(drop=True))
    print (df)
         fruit  ftype  price resource
    0    apple    one    100       us
    1    apple    two    150       us
    2    apple    avg    125      all
    3   banana    one    200       us
    4   banana    two    300       us
    5   banana    avg    250      all
    6    grape    one    400       us
    7    grape    two    500       us
    8    grape    avg    450      all
    9     kiwi  three    120       us
    10    kiwi    one    300       us
    11    kiwi    avg    210      all
    
    2019-12-25 21:52:30
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
RowKey与索引设计:技巧与案例分析 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载