m0_74246606 2022-11-15 17:47 采纳率: 60%
浏览 39
已结题

完成下列函数,根据数据框输出

1
def mean_type (df):

要求返回的数据是 'df' 每一列的平均值,和每一个唯一值

例子:
数据框
type a b c
index
0 x 1 0 1
1 x 0 0 1
2 y 1 0 1
输出
a b c
type
x 0.5 0.0 1.0
y 1.0 0.0 1.0

2
def last_type(df):

返回一个数据框,其中有'df'的最后一行和每一“type”里的唯一值

例子
数据框
type a b c
index
0 x 1 0 1
1 x 0 0 1
2 y 1 0 1
输出
a b c type
type
x 0 0 1 x
y 1 0 1 y

3
def last_type_org(df):

返回一个数据框,其中有'df'的最后一行和每一"type"里的唯一值,以及一个列名称为“org”该列的值是该行原始数据框的索引值

例子
数据框
type a b c
idx
0 x 1 0 1
1 x 0 0 1
2 y 1 0 1
输出
type a b c cor
type
x x 0 0 1 1
y y 1 0 1 2

  • 写回答

1条回答 默认 最新

  • 游一游走一走 2022-11-15 18:45
    关注
    import pandas
    
    def mean_type(df):
        return df.groupby('type').agg({'a': 'mean', 'b': 'mean', 'c': 'mean'})
    
    
    def last_type(df):
        last = df.groupby('type').last()
        last['type'] = last.index
        return last
    
    
    def last_type_org(df):
        df['cor'] = df.index
        last = df.groupby('type').last()
        last.insert(loc=0, column='type', value=last.index)
        return last
    
    if __name__ == '__main__':
        df = pandas.DataFrame({'type': ['x', 'x', 'y'], 'a': [1, 0, 1], 'b': [0, 0, 0], 'c': [1, 1, 1]})
        print(mean_type(df))
        print("\r\n")
        print(last_type(df))
        print("\r\n")
        print(last_type_org(df))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 11月16日
  • 已采纳回答 11月16日
  • 创建了问题 11月15日

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算