【问题标题】:Pandas group by a column and convert other columns to key:value pairPandas 按列分组并将其他列转换为键:值对
【发布时间】:2021-10-02 17:07:43
【问题描述】:

我的原始数据格式

我想把它转换成:

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    试试:

    output = df.groupby("id").apply(lambda x: x.to_json(orient="records")[1:-1])
    >>> output
    id
    1    {"id":1,"topic":1,"test1":"abc","test2":null,...
    2    {"id":2,"topic":3,"test1":null,"test2":null,...
    

    【讨论】:

    • 转换成列表怎么样? [{"id":1,"topic":1,"test1":"abc","test2":null,...}, {"id":1,"topic":2,"test1": "","test2":"fhg,..}]?@not_speshal
    • 删除 [1:-1]。使用df.groupby("id").apply(lambda x: x.to_json(orient="records"))
    猜你喜欢
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多