我有一段和下面描述的代码的和平,执行时间约为5秒,对于1000行文件来说相当长,所以我正在寻找优化方法,但我不知道如何改进现有版本。使用pandas数据框中的json对象优化解析文件
我有一个大的文件,包含在每行有效的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只提取了一些键值,获取应该是一个数据帧:
Groupe Id MotherName FatherName
Advanced 56 Laure James
Middle 11 Ann Nicolas
Advanced 6 Helen Franc
但一些关键,我需要在数据帧,在一些失踪json对象,所以我应该验证密钥是否存在,否则用空值填充相应的值。我继续以下方法:
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中实现它。
我有'AttributeError:'列表'对象没有属性'get''与这种方法!不要忘了我每行都有一个json的文件,也许这是一个问题。所以我需要遍历行来解析每个json – Amanda
,这样整个文件就不是json本身,但是这个文件的每一行都是有效的json – Amanda
它的工作原理除了不是字典而是嵌套的json!在这种情况下如何使用.get方法? @tdelaney – Amanda