Json 将数据帧转换为字典时嵌套/分组一系列列
我一直在努力解决如何将Pandas数据框转换为嵌套字典列表的问题,但我一直没有任何运气 我的第一个想法是将数据框转换成一个字典列表(其中Json 将数据帧转换为字典时嵌套/分组一系列列,json,python-3.x,pandas,dictionary,Json,Python 3.x,Pandas,Dictionary,我一直在努力解决如何将Pandas数据框转换为嵌套字典列表的问题,但我一直没有任何运气 我的第一个想法是将数据框转换成一个字典列表(其中users=users.to_dict(orient='records')),然后将“address”和“color\u preference”项合并到子列表中,但必须有更好的方法 我有这样一个数据帧: import pandas as pd users = pd.DataFrame({'email_address': ["email@email.com"],
users=users.to_dict(orient='records')
),然后将“address”和“color\u preference”项合并到子列表中,但必须有更好的方法
我有这样一个数据帧:
import pandas as pd
users = pd.DataFrame({'email_address': ["email@email.com"], 'status': ["active"], 'address': ["1 Eagle St"], 'suburb': ["BROOKLYN"], 'state': ["NY"], 'postcode': ["11201"], 'country': ["USA"], 'red': [False], 'orange': [True], 'yellow': [True], 'green': [True], 'blue': [False], 'indigo': [False], 'violet': [False]})
我正在尝试将其转换为以下格式:
{
"email_address":"email@email.com",
"status":"active",
"address":{
"address":"1 Eagle St",
"suburb":"Brooklyn",
"state":"NY",
"postcode":"11201",
"country":"USA"
},
"color_preference":{
"red":false,
"orange":true,
"yellow":true,
"green":true,
"blue":false,
"indigo":false,
"violet":false
}
}
您可以使用apply显式地执行此操作(我已经完成了前几步,但您可以执行所有地址/颜色): 您可以按位置拉出所有地址/颜色:
In [21]: users.columns[2:7]
Out[21]: Index(['address', 'suburb', 'state', 'postcode', 'country'], dtype='object')
In [22]: users.columns[7:]
Out[22]: Index(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'], dtype='object')
In [21]: users.columns[2:7]
Out[21]: Index(['address', 'suburb', 'state', 'postcode', 'country'], dtype='object')
In [22]: users.columns[7:]
Out[22]: Index(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'], dtype='object')