【发布时间】:2020-01-15 15:35:48
【问题描述】:
我需要将我的 DF 导出为特定的 JSON 格式,但我正在努力以正确的方式对其进行格式化。
我想创建一个带有 shop_details 的子部分,如果商店已知,它会显示商店的城市和位置,否则应该留空。
我的 DF 代码:
from pandas import DataFrame
Data = {'item_type': ['Iphone','Computer','Computer'],
'purch_price': [1200,700,700],
'sale_price': [1150,'NaN','NaN'],
'city': ['NaN','Los Angeles','San Jose'],
'location': ['NaN','1st street', '2nd street']
}
DF 看起来像这样:
item_type purch_price sale_price city location
0 Iphone 1200 1150 NaN NaN
1 Computer 700 NaN Los Angeles 1st street
2 Computer 700 NaN San Jose 2nd street
输出格式应如下所示:
[{
"item_type": "Iphone",
"purch_price": "1200",
"sale_price": "1150",
"shop_details": []
},
{
"item_type": "Computer",
"purch_price": "700",
"sale_price": "600",
"shop_details": [{
"city": "Los Angeles",
"location": "1st street"
},
{
"city": "San Jose",
"location": "2nd street"
}
]
}
]
【问题讨论】:
-
你能展示你为解决这个问题所做的努力吗?
标签: python json pandas dataframe export