我有多個 JSON 檔案需要轉換為一個 CSV 檔案
這些是示例 JSON 代碼
試用1.json
{
"Product":{
"one":"Desktop Computer",
"two":"Tablet",
"three":"Printer",
"four":"Laptop"
},
"Price":{
"five":700,
"six":250,
"seven":100,
"eight":1200
}}
tryout2.json
{
"Product":{
"one":"dell xps tower",
"two":"ipad",
"three":"hp office jet",
"four":"macbook"
},
"Price":{
"five":500,
"six":200,
"seven":50,
"eight":1000
}}
這是我為轉換這 2 個 json 檔案而撰寫的 python 代碼
import pandas as pd
df1 = pd.read_json('/home/mich/Documents/tryout.json')
print(df1)
df2 = pd.read_json('/home/mich/Documents/tryout2.json')
print(df2)
df = pd.concat([df1, df2])
df.to_csv ('/home/mich/Documents/tryout.csv', index = None)
result = pd.read_csv('/home/mich/Documents/tryout.csv')
print(result)
但是我沒有得到我需要的結果。如何在一個列(產品和價格)中列印第一個 json 檔案,在下一列中列印第二個檔案?(通過鏈接查看影像)
我得到的結果
[
]
我需要的結果
[
]
uj5u.com熱心網友回復:
您可以先創建產品和價格的組合列,然后將它們連接起來。
我正在使用,axis = 1因為我希望它們并排組合。(列)
axis = 0將按行組合。
import pandas as pd
df1 = pd.read_json('/home/mich/Documents/tryout.json')
df1['product_price'] = df1['Product'].fillna(df1['Price'])
df2 = pd.read_json('/home/mich/Documents/tryout2.json')
df2['product_price'] = df2['Product'].fillna(df2['Price'])
pd.concat([df1['product_price'], df2['product_price']],axis=1)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365300.html
