我有一個資料框,我想通過選擇列將其轉換為 json 格式。而且由于我有很多線,我不能手工完成所有事情
我有一個看起來像這樣的資料框:
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4', np.nan],
'Price': [22000,25000,27000,35000, 29000],
'Liscence Plate': ['ABC 123', 'XYZ 789', 'CBA 321', 'ZYX 987', 'DEF 456']}
df = pd.DataFrame(Cars,columns= ['Brand', 'Price', 'Liscence Plate'])
Brand Price Liscence Plate
0 Honda Civic 22000 ABC 123
1 Toyota Corolla 25000 XYZ 789
2 Ford Focus 27000 CBA 321
3 Audi A4 35000 ZYX 987
4 NaN 29000 DEF 456
5 Ford 27000 DEF 466
6 Audi A1 35000 ABC 123
我必須轉換為:
data = {"form": [
{"Liscence Plate": "ABC 123",
"Brand": ["Honda Civic", "Audi A1"
],
"Price": ["22000", "35000"]},
{"Liscence Plate": "XYZ 789",
"Brand": ["Toyota Corolla",
],
"Price": ["25000"]},
{"Liscence Plate": "CBA 321",
"Brand": ["Ford Focus",
],
"Price": ["27000"]},
{"Liscence Plate": "ZYX 987",
"Brand": ["Audi A4",
],
"Price": ["35000"]},
{"Liscence Plate": "DEF 456",
"Brand": ["NaN", "Ford"
],
"Price": ["29000", "27000"]}
uj5u.com熱心網友回復:
看看.to_json() 函式。它將允許您輕松地將 DataFrame 轉換為 json。您可以通過提供orient引數來更改 json 的架構。
這將作業得很好,但它不會為您提供品牌和價格鍵的串列。如果您想要更大的靈活性,您可以首先使用.to_dict()具有相同orient引數的函式,進行更改,然后使用json.dump()轉換為 json 。
編輯:根據您的編輯,我認為您要先按車牌分組?在這種情況下,你可以這樣做:
df.groupby('Liscence Plate').agg(list).reset_index().to_json('records')
聚合到串列并轉換為 json。
uj5u.com熱心網友回復:
所以你想要這個?
df.to_json(orient='records')
輸出:
[{
"Brand": "Honda Civic",
"Price": 22000,
"Liscence Plate": "ABC 123"
}, {
"Brand": "Toyota Corolla",
"Price": 25000,
"Liscence Plate": "XYZ 789"
}, {
"Brand": "Ford Focus",
"Price": 27000,
"Liscence Plate": "CBA 321"
}, {
"Brand": "Audi A4",
"Price": 35000,
"Liscence Plate": "ZYX 987"
}, {
"Brand": null,
"Price": 29000,
"Liscence Plate": "DEF 456"
}]
編輯:
df = df.groupby('Liscence Plate').agg({'Brand': lambda x: list(x), 'Price': lambda x: list(x)}).reset_index()
df.to_json(orient='records')
[{
"Liscence Plate": "ABC 123",
"Brand": ["Honda Civic"],
"Price": [22000]
}, {
"Liscence Plate": "CBA 321",
"Brand": ["Ford Focus"],
"Price": [27000]
}, {
"Liscence Plate": "DEF 456",
"Brand": [null, "Ford F-150"],
"Price": [29000, 33000]
}, {
"Liscence Plate": "XYZ 789",
"Brand": ["Toyota Corolla"],
"Price": [25000]
}, {
"Liscence Plate": "ZYX 987",
"Brand": ["Audi A4"],
"Price": [35000]
}]
uj5u.com熱心網友回復:
使用pandas.DataFrame.iterrows和“手動”構建結果。
data = {'form' : [
{k:[str(s[k])] if t == list else str(s[k])
for k, t in (("Liscence Plate", str), ("Brand", list), ("Price", list))}
for _, s in df.iterrows()]
}
>>> data
{'form': [
{'Brand': ['Honda Civic'], 'Liscence Plate': 'ABC 123', 'Price': ['22000']},
{'Brand': ['Toyota Corolla'], 'Liscence Plate': 'XYZ 789', 'Price': ['25000']},
{'Brand': ['Ford Focus'], 'Liscence Plate': 'CBA 321', 'Price': ['27000']},
{'Brand': ['Audi A4'], 'Liscence Plate': 'ZYX 987', 'Price': ['35000']},
{'Brand': ['nan'], 'Liscence Plate': 'DEF 456', 'Price': ['29000']}
]
}
這與您要查找的內容非常接近。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/376142.html
上一篇:Discordbot客戶端未定義
