我有以下代碼JSON從目錄中讀取一些檔案并在一些預處理后回傳它們。但是,其中一些是字典,因此它們沒有所需的列。結果,我收回了這個錯誤
KeyError: "None of [Index(['aaa', 'xxx'], dtype='object')] are in the [columns]"]
如何忽略它們并繼續處理其他JSON檔案?也許是一個try-except程式?
import os, json
import pandas as pd
path_to_json = 'C:/Users/aaa/Desktop/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
def func(s):
try:
return eval(s)
except:
return dict()
list_of_df=[]
for i in range(len(json_files)):
file_name = json_files[i]
df = pd.read_json(file_name, lines=True)
df= df[['columnx']]
df = df['columnx'].apply(func)
df=pd.json_normalize(df)
df=pd.DataFrame(df[["xxx", "aaa"]])
list_of_df.append(df)
df=pd.concat(list_of_df)
df = df[['Index','xxx', 'aaa']]
df.head()
uj5u.com熱心網友回復:
您必須添加在回圈 json 檔案的 for 回圈中添加的 try-except 塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/361627.html
