我正在嘗試將 JSON 檔案轉換為資料框,并在最后將其保存為 CSV 檔案。好吧,我可以使用 Jupyter 或 Colab 來做到這一點,但是當我嘗試使用本地 python 編譯器時,我遇到了很多錯誤。
這是我在 Colab 上運行的代碼
import pandas as pd
import datetime
# reading json file
df = pd.read_json(path_or_buf=CONFIG_PROPERTIES)
# normalizing json file
df_items_normalized = pd.json_normalize(data=df.orders, sep='_', record_path='items', meta=['error', 'file','order_id'])
# define parameters to save in csv
today = datetime.datetime.today().strftime('%Y_%m_%d')
path = "/output/pedidos_weedu_" today ".csv"
# saving to csv
df_items_normalized.to_csv(path, index=False)
這是我嘗試通過 Pycharm 時的代碼
import pandas as pd
import datetime
import json
import os
CWD = os.getcwd()
JSON_CONFIG_FILE_PATH = '%s/%s' % (CWD, '12-11-2021.json')
CONFIG_PROPERTIES = {}
try:
with open(JSON_CONFIG_FILE_PATH) as data_file:
CONFIG_PROPERTIES = json.load(data_file)
except IOError as e:
print(e)
print('IOError: Unable to open config.json.')
exit(1)
print(CONFIG_PROPERTIES)
# reading json file
df = pd.read_json(path_or_buf=CONFIG_PROPERTIES)
# normalizing json file
df_items_normalized = pd.json_normalize(data=df.orders, sep='_', record_path='items', meta=['error', 'file','order_id'])
# define parameters to save in csv
today = datetime.datetime.today().strftime('%Y_%m_%d')
path = "/output/pedidos_weedu_" today ".csv"
# saving to csv
df_items_normalized.to_csv(path, index=False)
這是我正在處理的JSON檔案
uj5u.com熱心網友回復:
我稍微改變了你的代碼:
import pandas as pd
import datetime
import json
import os
from pandas.io.json import json_normalize as jn
CWD = os.getcwd()
JSON_CONFIG_FILE_PATH = "%s/%s" % (CWD, "12-11-2021.json")
print(JSON_CONFIG_FILE_PATH)
CONFIG_PROPERTIES = {}
try:
with open(JSON_CONFIG_FILE_PATH) as data_file:
CONFIG_PROPERTIES = json.load(data_file)
except IOError as e:
print(e)
print("IOError: Unable to open config.json.")
exit(1)
print(CONFIG_PROPERTIES)
df = pd.read_json(path_or_buf=JSON_CONFIG_FILE_PATH)
df_items_normalized = jn(
data=df.orders, sep="_", record_path="items", meta=["error", "file", "order_id"]
)
# define parameters to save in csv
today = datetime.datetime.today().strftime("%Y_%m_%d")
path = "./" today ".csv"
# saving to csv
df_items_normalized.to_csv(path, index=False)
from pandas.io.json import json_normalize as jn來自這個答案的這一行。
我真的不明白為什么這個答案會被否定!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360298.html
下一篇:為什么我的預定作業會自動運行?
