美文网首页
Pandas中group+apply应用

Pandas中group+apply应用

作者: 测试探索 | 来源:发表于2022-01-12 11:14 被阅读0次
    import pandas as pd
    
    dict_1 = {"time": ["2019-11-02", "2019-11-03", "2019-11-04", "2019-11-05",
                       "2019-12-02", "2019-12-03", "2019-12-04", "2019-12-05"],
              "pos": ["A", "A", "C", "D", "E", "E", "G", "H"],
              "value1": [10, 20, 30, 40, 50, 60, 70, 80],
              "value2": [100, 200, 300, 400, 500, 600, 700, 800],
              "value3": [50, 20, 30, 90, 50, 60, 80, 80],
              "value4": [10, 30, 90, 40, 60, 60, 70, 80]}
    
    df_1 = pd.DataFrame(dict_1, columns=["time", "pos", "value1", "value2", "value3", "value4"])
    print("\n", "df_1", "\n", df_1, "\n")
    
    #第一种方式
    def get_f5(x):
        print("x的结果是:\n",x) #查看x的类型
        print("x的值是:\n",x.values) #查看x的类型
        print("x转为list是:\n",x.values.tolist()) #查看x的类型
        print("最终输出:\n",dict(x.values.tolist())) #查看x的类型
        return dict(x.values.tolist())
    
    data = df_1.groupby("pos")[["value1","value2"]].apply(get_f5)
    print("第一种方式:",data)
    # # 第二种方式
    dict_map = df_1.groupby('pos')[['value1','value2']].apply(lambda g: dict(g.values.tolist()))
    print("第二种方式:",dict_map)
    dict_result = df_1.groupby('pos')[['value1','value2']].apply(lambda g: dict(g.values.tolist())).to_dict()
    print("最终结果:",dict_result)
    
    df_1结果
    image.png
    get_f5方法里的打印
    image.png
    两种方式的运行结果
    image.png
    最终需要的格式
    image.png

    相关文章

      网友评论

          本文标题:Pandas中group+apply应用

          本文链接:https://www.haomeiwen.com/subject/vjfwcrtx.html