【发布时间】:2021-12-31 01:00:11
【问题描述】:
我有以下代码从目录中读取一些JSON 文件并在一些预处理后返回它们。但是,其中一些是 dict,因此它们没有所需的列。结果,我收回了这个错误
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()
【问题讨论】:
-
欢迎来到 SO。您必须在迭代 json 文件的 for 循环中添加 try except 块。
-
您好,谢谢。是的,在 for 中的 try-except continue 会成功。谢谢
-
很高兴知道,请在下面接受我的回答。
标签: python json python-3.x parsing