如何将列表转换为嵌套在列表中的字典?

2024-05-19 19:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始使用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": [
    [15.0, 10.1],    [42.2, 42.3],    [43.4, 43.5],    [89.0, 5.0],    [45.8, 45.9]
  ]
}

我尝试使用df.to_dictwith list作为定向参数,但结果是x和y的两个长列表,而不是许多对列表

对于python用户来说,这可能是一个小问题,提前感谢您的帮助


Tags: columnstoapidataframedf列表data参数
3条回答

您可以这样做:-

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)

相关问题 更多 >