如何将大熊猫DF转换为这种JSON结构?

发布于 2025-01-25 13:21:38 字数 1053 浏览 0 评论 0原文

假设我有熊猫df这样:

| name   | color of clothing | age |occupation|
| John   | yellow            | 34  | janitor  |
| Carl   | red               | 27  | doctor   |
| Claire | green             | 33  | teacher  |
| Lisa   | blue              | 21  | Student  |
|........|...................| ....|..........|

我想以这样的json格式进行改造:

[
{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
},
{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
},
{ "name": "Claire",
"color of clothing": "green",
"age":"33",
"occupation": "teacher"
},
{ "name": "Lisa",
"color of clothing": "blue",
"age":"21",
"occupation": "student"
}
]

我该怎么做?我最近的比赛是使用df.to_json(orient =“ index”),但是我得到的是这样的结构:

{"0":{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
}
},
"1":{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
}}
...

真的很感谢任何帮助!

Let's say I have a pandas df like this:

| name   | color of clothing | age |occupation|
| John   | yellow            | 34  | janitor  |
| Carl   | red               | 27  | doctor   |
| Claire | green             | 33  | teacher  |
| Lisa   | blue              | 21  | Student  |
|........|...................| ....|..........|

I would like to transform it in a json format like this:

[
{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
},
{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
},
{ "name": "Claire",
"color of clothing": "green",
"age":"33",
"occupation": "teacher"
},
{ "name": "Lisa",
"color of clothing": "blue",
"age":"21",
"occupation": "student"
}
]

How can I do this? The nearest match I had was using df.to_json(orient="index") but what I've got was a structure like this:

{"0":{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
}
},
"1":{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
}}
...

Would be really thankful for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乱了心跳 2025-02-01 13:21:38

使用df.to_dict('Records')

>>> df
   a  b  c  d
0  1  1  1  1
1  2  2  2  2
>>> df.to_dict('records')
[{'a': 1, 'b': 1, 'c': 1, 'd': 1}, {'a': 2, 'b': 2, 'c': 2, 'd': 2}]

Use df.to_dict('records')

>>> df
   a  b  c  d
0  1  1  1  1
1  2  2  2  2
>>> df.to_dict('records')
[{'a': 1, 'b': 1, 'c': 1, 'd': 1}, {'a': 2, 'b': 2, 'c': 2, 'd': 2}]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文