![](/img/trans.png)
[英]Convert dictionary with nested lists to a specific pandas df structure
[英]How to convert pandas df to dictionary with lists nested in the list?
我最近开始使用 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 一起用作 orient 参数,但结果是 2 个 x 和 y 长列表,而不是许多对列表。
对于 python 用户来说可能是微不足道的问题,提前感谢您的帮助!
通过DataFrame.to_numpy
将值转换为 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']]}
你可以这样做:-
res = {'Points' : [[row['x'], row['y']] for i, row in df.iterrows()]}
print(res)
Output:-
{'Points': [['15.0', '10.1'], ['42.2', '42.3'], ['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
这里是 go:
output = {}
for i, row in df.iterrows():
output['Points'] = [[row['x'], row['y']]
print(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.