Python 如何将列表转换为嵌套在列表中的字典?
我最近开始使用python,现在正在使用API请求。我需要将dataframe转换为嵌套在列表中的列表字典 如何转换dfPython 如何将列表转换为嵌套在列表中的字典?,python,json,pandas,dictionary,Python,Json,Pandas,Dictionary,我最近开始使用python,现在正在使用API请求。我需要将dataframe转换为嵌套在列表中的列表字典 如何转换df data = {'x': ['15.0', '42.2','43.4','89.0','45.8'], 'y': ['10.1', '42.3','43.5','5.0','45.9'] } df = pd.DataFrame (data, columns = ['x','y']) 到嵌套在列表中的列表字典 { "Points":
data = {'x': ['15.0', '42.2','43.4','89.0','45.8'],
'y': ['10.1', '42.3','43.5','5.0','45.9']
}
df = pd.DataFrame (data, columns = ['x','y'])
到嵌套在列表中的列表字典
{
"Points": [
[15.0, 10.1], [42.2, 42.3], [43.4, 43.5], [89.0, 5.0], [45.8, 45.9]
]
}
我尝试使用df.to_dict
,将list作为定向参数,但结果是x和y的两个长列表,而不是许多对列表
对于python用户来说,这可能是一个小问题,提前感谢您的帮助 您可以这样做:-
res = {'Points' : [[row['x'], row['y']] for i, row in df.iterrows()]}
print(res)
输出:-
{'Points': [['15.0', '10.1'], ['42.2', '42.3'], ['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
将值转换为numpy数组,然后再转换为列表:
d = {"Points":df.to_numpy().tolist()}
#if there is more columns
#d = {"Points":df[['x','y']].to_numpy().tolist()}
print (d)
{'Points': [['15.0', '10.1'], ['42.2', '42.3'],
['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
给你:
output = {}
for i, row in df.iterrows():
output['Points'] = [[row['x'], row['y']]
print(output)
我以前不知道。谢谢。:)