Fed*_*Fed 2 python csv json nested pandas
我正在尝试将嵌套的 json 转换为 csv 文件,但我正在努力解决文件结构所需的逻辑:它是一个包含 2 个对象的 json,我只想将其中一个对象转换为 csv,这是带嵌套的列表。
我在这篇博文中发现了非常有用的“扁平化”json 信息。我基本上已经根据我的问题调整了它,但它仍然对我不起作用。
我的 json 文件如下所示:
{
"tickets":[
{
"Name": "Liam",
"Location": {
"City": "Los Angeles",
"State": "CA"
},
"hobbies": [
"Piano",
"Sports"
],
"year" : 1985,
"teamId" : "ATL",
"playerId" : "barkele01",
"salary" : 870000
},
{
"Name": "John",
"Location": {
"City": "Los Angeles",
"State": "CA"
},
"hobbies": [
"Music",
"Running"
],
"year" : 1985,
"teamId" : "ATL",
"playerId" : "bedrost01",
"salary" : 550000
}
],
"count": 2
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我的代码如下所示:
{
"tickets":[
{
"Name": "Liam",
"Location": {
"City": "Los Angeles",
"State": "CA"
},
"hobbies": [
"Piano",
"Sports"
],
"year" : 1985,
"teamId" : "ATL",
"playerId" : "barkele01",
"salary" : 870000
},
{
"Name": "John",
"Location": {
"City": "Los Angeles",
"State": "CA"
},
"hobbies": [
"Music",
"Running"
],
"year" : 1985,
"teamId" : "ATL",
"playerId" : "bedrost01",
"salary" : 550000
}
],
"count": 2
}
Run Code Online (Sandbox Code Playgroud)
我想要获得的是 csv 中每张票的 1 行,标题为:
Name,Location_City,Location_State,Hobbies_0,Hobbies_1,Year,TeamId,PlayerId,Salary。
我真的很感激任何可以点击的东西!谢谢你!
事实上,我最近写了一个名为cherrypicker的包来处理这类事情,因为我不得不经常这样做!
我认为下面的代码会给你你所追求的:
from cherrypicker import CherryPicker
import json
import pandas as pd
with open('file.json') as file:
data = json.load(file)
picker = CherryPicker(data)
flat = picker['tickets'].flatten().get()
df = pd.DataFrame(flat)
print(df)
Run Code Online (Sandbox Code Playgroud)
这给了我输出:
Location_City Location_State Name hobbies_0 hobbies_1 playerId salary teamId year
0 Los Angeles CA Liam Piano Sports barkele01 870000 ATL 1985
1 Los Angeles CA John Music Running bedrost01 550000 ATL 1985
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令安装该软件包:
pip install cherrypicker
Run Code Online (Sandbox Code Playgroud)
...还有更多文档和指南https://cherrypicker.readthedocs.io。