从pandas Dataframe 创建带有列表的嵌套json

4nkexdtk  于 2023-03-16  发布在  其他
关注(0)|答案(2)|浏览(134)

我有一个包含以下列的DataFrame:id, jan_x, jan_y, feb_x, feb_y, ..., dec_x, dec_y,我希望导出为json,其结构如下:

{
    "id1": [
        [jan_x, feb_x, ..., dec_x],
        [jan_y, feb_y, ..., dec_y]
    ],
    "id2": [
        [jan_x, feb_x, ..., dec_x],
        [jan_y, feb_y, ..., dec_y]
    ]
}

初始键,例如id1,对应于我的 Dataframe 的id列中的一个id。如果没有任何自定义解析函数,是否有一种直接的函数方法来实现这一点?我尝试将其作为json转储,但没有捕获所需的列表结构。
这里是一个样本 Dataframe 只有两个月。

data = {'id': ['1', '2', '3', '4'],
        'jan_x': [1, 2, 3, 4],
        'jan_y': [5, 6, 7, 8],
        'feb_x': [9, 10, 11 12],
        'feb_y': [13 14, 15, 16]}
  
df = pd.DataFrame(data)

样本输出:

{
    "1": [
        [1, 9],
        [5, 13]
    ],
    "2": [
        [2, 10],
        [6, 14]
    ],
    "3": [
        [3, 11],
        [7, 15]
    ],
    "4": [
        [4, 12],
        [8, 16]
    ]
}
js4nwp54

js4nwp541#

我不确定您所说的“任何自定义解析函数”是什么意思,但这里是我的尝试。
解决方案使用iterrows来遍历行。对于每一行,我使用上面定义的x_columns变量获取以_x结尾的列,对于以_y结尾的列也是如此。row[x_columns]将值作为Pandas系列提供给您,因此你需要在添加之前把它转换成一个列表来适应你想要的格式。2我把所有这些都附加到一个结果变量中,并在最后打印这个结果变量。

import pandas as pd

# Create a dataframe for demo
data={"id":[15,12,13,22,32,11], "jan_x":[15,12,13,22,32,11],"jan_y":[12,21,23,22,56,11], "feb_x":[15,12,13,22,32,11],"feb_y":[12,21,23,22,56,11]}
df=pd.DataFrame(data)

# Get columns that ends with _x and _y
x_columns = [col for col in df if col.endswith('_x')]
y_columns = [col for col in df if col.endswith('_y')]

# Iterate through rows
results = []
for index, row in df.iterrows():
  results.append({
    "id"+str(row['id']): [
        list(row[x_columns]),
        list(row[y_columns])
        ]
    })
    
print(result)

下面是我的示例输入:

id  jan_x  jan_y  feb_x  feb_y
0  15     15     12     15     12
1  12     12     21     12     21
2  13     13     23     13     23
3  22     22     22     22     22
4  32     32     56     32     56
5  11     11     11     11     11

下面是输出:

[{'id15': [[15, 15], [12, 12]]}, 
 {'id12': [[12, 12], [21, 21]]}, 
 {'id13': [[13, 13], [23, 23]]}, 
 {'id22': [[22, 22], [22, 22]]}, 
 {'id32': [[32, 32], [56, 56]]}, 
 {'id11': [[11, 11], [11, 11]]}
 ]
sy5wg1nm

sy5wg1nm2#

更新

在按通用后缀(“x”,“y”,...)聚合后使用to_dict('list')

import json

out = (df.rename(columns=lambda x: x.split('_')[-1])
         .set_index('id').groupby(level=0, axis=1, sort=False)
         .agg(lambda x: x.values.tolist()).T.to_dict('list'))
jd = json.dumps(out, indent=4)

输出:

>>> out
{'1': [[1, 9], [5, 13]],
 '2': [[2, 10], [6, 14]],
 '3': [[3, 11], [7, 15]],
 '4': [[4, 12], [8, 16]]}

相关问题