我希望优化下面的代码,这需要大约5秒,这对于一个只有1000行的文件来说太慢了。在
我有一个大文件,其中每一行都包含有效的JSON,每个JSON看起来如下所示(实际数据要大得多,并且是嵌套的,所以我用这个JSON片段来说明):
{"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中只提取一些键值,以获得结果数据帧:
^{pr2}$但是我在dataframe中需要的一些键在一些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行文件的运行时优化为<;=2秒。在PERL中,同样的解析函数需要<;1秒,但我需要用Python实现它。在
如果在初始化过程中只需一步就可以构建数据帧,那么您将获得最佳性能。},这样您就知道链式get可以工作了。在
DataFrame.from_record
获取一个元组序列,您可以从一次读取一条记录的生成器中提供这些元组。您可以使用get
更快地解析数据,当找不到项时,它将提供一个默认参数。我创建了一个名为dummy
的空dict
来传递中间的{我创建了1000个记录数据集,在我的破笔记本上,时间从18秒变为0.06秒。很不错。在
关键部分是不将每一行追加到循环中的数据帧。您希望将集合保存在一个list或dict容器中,然后一次连接所有这些集合。您还可以使用一个简单的返回默认值的
get
来简化if/else
结构(例如。np.nan公司)如果在字典中找不到该项。在相关问题 更多 >
编程相关推荐