Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列表转换为嵌套在列表中的字典?_Python_Json_Pandas_Dictionary - Fatal编程技术网

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

Python 如何将列表转换为嵌套在列表中的字典?,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":

我最近开始使用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_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)

我以前不知道。谢谢。:)