我有一段和下面描述的代碼的和平,執行時間約爲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