我正在處理 csv 檔案。csv表檔案結構如下
| 品牌 | 楷模 | 2021_價格 | 2020_價格 |
|---|---|---|---|
| 雪佛蘭 | 遍歷 | 320000 | 24000 |
| 雪佛蘭 | 春分 | 23000 | 18000 |
| 雪佛蘭 | 開拓者 | 13000 | 14000 |
這是我自己嘗試過的
json_dict = {}
for index,row in df.iterrows():
data=(
{row[0]:{
''.join(str(row[1])):
{
"2021":' '.join(str(row[2]).split()),
'2020':' '.join(str(row[3]).split()),
}
}
}
)
json_dict.update(data)
我把它作為輸出
{
"chevrolet":{
"Traverse":{
"2021":"320000",
"2020":"24000",
},
"chevrolet":{
"Equinox":{
"2021":"23000",
"2020":"18000",
}
}
但預期的字典是
{
"chevrolet":{
"Traverse":{
"2021":"320000",
"2020":"24000"
},
"Equinox":{
"2021":"23000",
"2020":"18000"
}
}
這是檔案樣本
NISSAN Patrol Platinum City 1,260,000,000.00 UZS Nan
NISSAN Qasgqai 315,000,000.00 UZS 315,000,
NISSAN X-Trail 367,500,000.00 UZS Nan
uj5u.com熱心網友回復:
如果我理解正確,您想按“品牌”分組,然后創建一個字典:
out = {}
for b, g in df.groupby("brands"):
out[b] = {
row["models"]: {
"2020": row["2020_price"],
"2021": row["2021_price"],
}
for _, row in g.iterrows()
}
print(out)
印刷:
{
"chevrolet": {
"Traverse": {"2020": 24000, "2021": 320000},
"Equinox": {"2020": 18000, "2021": 23000},
"Trailblazer": {"2020": 14000, "2021": 13000},
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476894.html
上一篇:內容旋轉-Python
