【问题标题】:How can i create a nested json in pandas from a dataframe using one column value as key?如何使用一列值作为键从数据框中创建嵌套的 json?
【发布时间】:2020-03-19 22:30:29
【问题描述】:

我有一个数据框 df,如下所示:

col1 | col2| col3| col4| col5
_____|_____|_____|_____|______
 1   |  X  |  A  |  a  |  x
 1   |  X  |  B  |  b  |  y

我需要将其转换如下:

{'col1':'1', 'col2':'X' , 'A':{ 'col4':'a', 'col5':'x'}, 'B':{'col4':'b', 'col5':'y'}}

我尝试过以下代码:

json= df.groupby(['col1,'col2'],as_index='False')[['col3','col4','col5']]
                   .apply(lambda x:x.set_index('col3').to_dict(orient='index'))
                   .reset_index()
                   .to_json(orient='records'))

它给了我输出:

[{'col1':'1', 'col2':'X' ,'0':{ 'A':{ 'col4':'a', 'col5':'x'}, 'B':{'col4':'b', 'col5':'y'} }}]

我尝试使用to_dict 代替to_json,但效果不佳。以上是我最接近满足我的要求。我假设“0”代表索引。有什么办法可以去掉吗?

【问题讨论】:

  • 你要删除什么?

标签: python json pandas dictionary nested


【解决方案1】:

用途:

json= (df.groupby(['col1','col2','col3'],as_index='False')[['col4','col5']]
                   .apply(lambda x: dict(x.values))
                   .unstack()
                   .reset_index()
                   .to_json(orient='records')
)
print (json)
[{"col1":1,"col2":"X","A":{"a":"x"},"B":{"b":"y"}}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2020-12-22
    • 2020-01-21
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多