我如何在 Pandas 中讀取下面的 json:
[
{
"DataVal": {
"sales": "0.00000",
"cost": "926.00000",
"os": "And",
"hr": "0",
"_id": "34358",
"month": "10",
"date": "2021-10-11"
}
},
{
"DataVal": {
"sales": "0.00000",
"cost": "830.00000",
"os": "And",
"hr": "0",
"_id": "24158",
"month": "10",
"date": "2021-01-02"
}
},
{
"DataVal": {
"sales": "0.00000",
"cost": "128.00000",
"os": "And",
"hr": "0",
"_id": "23358",
"month": "10",
"date": "2021-10-03"
}
}
電流輸出
| 資料值 |
|---|
| {'sales': '0.00000', 'cost': '96.00000', 'os': 'And', 'hr': '0', '_id': '24358', 'month': '10', '日期':'2021-10-01'} |
| {'sales': '0.00000', 'cost': '96.00000', 'os': 'And', 'hr': '0', '_id': '24358', 'month': '10', '日期':'2021-10-01'} |
預期輸出:
| 銷售量 | 成本 | 作業系統 |
|---|---|---|
| 0.000 | 234 | 和 |
上表與其他附加列,如 os、hr、_id、month
uj5u.com熱心網友回復:
將 JSON 檔案讀入data使用json
import json
with open('path/to/json.json') as f:
data = json.load(f)
或者,如果它來自 API 呼叫(使用requests)
data = response.json()
那么你只需要
df = pd.DataFrame(rec['DataVal'] for rec in data)
輸出:
>>> df
sales cost os hr _id month date
0 0.00000 926.00000 And 0 34358 10 2021-10-11
1 0.00000 830.00000 And 0 24158 10 2021-01-02
2 0.00000 128.00000 And 0 23358 10 2021-10-03
設定:
data = [
{
"DataVal": {
"sales": "0.00000",
"cost": "926.00000",
"os": "And",
"hr": "0",
"_id": "34358",
"month": "10",
"date": "2021-10-11"
}
},
{
"DataVal": {
"sales": "0.00000",
"cost": "830.00000",
"os": "And",
"hr": "0",
"_id": "24158",
"month": "10",
"date": "2021-01-02"
}
},
{
"DataVal": {
"sales": "0.00000",
"cost": "128.00000",
"os": "And",
"hr": "0",
"_id": "23358",
"month": "10",
"date": "2021-10-03"
}
}
]
uj5u.com熱心網友回復:
嘗試這個:
import json
with open('your path') as f:
data = json.load(f)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366636.html
下一篇:如何從CSV形成JSON
