【发布时间】:2016-06-09 06:02:03
【问题描述】:
我正在优化下面的代码,大约需要 5 秒,这对于只有 1000 行的文件来说太慢了。
我有一个大文件,其中每一行都包含有效的 JSON,每个 JSON 如下所示(实际数据要大得多且嵌套,因此我使用此 JSON sn-p 进行说明):
{"location":{"town":"Rome","groupe":"Advanced",
"school":{"SchoolGroupe":"TrowMet", "SchoolName":"VeronM"}},
"id":"145",
"Mother":{"MotherName":"Helen","MotherAge":"46"},"NGlobalNote":2,
"Father":{"FatherName":"Peter","FatherAge":"51"},
"Teacher":["MrCrock","MrDaniel"],"Field":"Marketing",
"season":["summer","spring"]}
我需要解析这个文件,以便从每个 JSON 中仅提取一些键值,以获得结果数据帧:
Groupe Id MotherName FatherName
Advanced 56 Laure James
Middle 11 Ann Nicolas
Advanced 6 Helen Franc
但是我在数据框中需要的一些键在一些 JSON 对象中丢失了,所以我应该验证键是否存在,如果不存在,则用 Null 填充相应的值。我使用以下方法:
df = pd.DataFrame(columns=['group', 'id', 'Father', 'Mother'])
with open (path/to/file) as f:
for chunk in f:
jfile = json.loads(chunk)
if 'groupe' in jfile['location']:
groupe = jfile['location']['groupe']
else:
groupe=np.nan
if 'id' in jfile:
id = jfile['id']
else:
id = np.nan
if 'MotherName' in jfile['Mother']:
MotherName = jfile['Mother']['MotherName']
else:
MotherName = np.nan
if 'FatherName' in jfile['Father']:
FatherName = jfile['Father']['FatherName']
else:
FatherName = np.nan
df = df.append({"groupe":group, "id":id, "MotherName":MotherName, "FatherName":FatherName},
ignore_index=True)
我需要将整个 1000 行文件的运行时间优化为
【问题讨论】:
-
你应该使用 Python 的
dict.get(key, default)method which optionally takes adefaultvalue for whenkeyis not found。这也使您的内循环代码更加紧凑和清晰 4 倍。但是您可能可以使用dict.update或defaultdict来进一步减少。
标签: python json performance pandas memory