2017-10-08 237 views
1

我正在使用熊貓來處理數據幀。我創建了一個數據框,其行數如下:[id, vector] 其中,id是字符串類型,而vector是字典類型。Python將字典寫入csv並從csv讀取字典

現在,當我寫一個CSV文件中的行看起來像這樣(CSV文件):

25377bc2-d3b6-4699-a466-6b9f544e8ba3 {u'sport>sports event>world championship': 0.5058, u'sport>sports event': 0.7032, u'sport>soccer': 0.6377, u'lifestyle and leisure>game': 0.4673, u'sport>sports event>world cup': 0.6614, u'sport>sports event>international tournament': 0.454, u'sport>sports event>national tournament': 0.541, u'sport': 0.9069, u'sport>sports organisations>international federation': 0.5046, u'sport>sports organisations': 0.6982}  

我試着閱讀從CSV回大熊貓的數據幀,但是當我看看曾經是dict它現在是<type 'str'>

我知道我可以解決它與泡菜和保存熊貓數據幀到一個泡菜文件。但是,有沒有辦法正確地讀取CSV(其中在它的載體是型詞典)

+0

是否可以保存爲'json'? – jezrael

+0

是的。我會很高興看到一個json解決方案,並且您的建議將很樂意聽到 –

回答

2

我認爲你可以使用json什麼是更好的結構csv爲節省dicts

對於寫使用to_json和閱讀read_json與參數orient='records',感謝piRSquared發表評論:

df = pd.DataFrame({'vector':[{'a':1, 'b':3}, {'a':4, 'b':6}], 'ID':[2,3]}) 
print (df) 
    ID   vector 
0 2 {'b': 3, 'a': 1} 
1 3 {'b': 6, 'a': 4} 

df.to_json('file.json', orient='records') 
    ID   vector 
0 2 {'b': 3, 'a': 1} 
1 3 {'b': 6, 'a': 4} 

df = pd.read_json('file.json', orient='records') 
print (df) 

print (df.applymap(type)) 
       ID   vector 
0 <class 'int'> <class 'dict'> 
1 <class 'int'> <class 'dict'> 

EDIT1:

如果是列必要的順序相同,指數值使用:

df.to_json('file.json', orient='split') 

df = pd.read_json('file.json', orient='split') 
+0

我認爲'orient ='records''可能更合適,因爲生成的'json'只有'id'和'vector'鍵。 – piRSquared

+0

@EranMoshe - 對我來說它工作的很好,我的解決方案中存在真實數據的問題嗎? – jezrael

+0

我檢查了東方='記錄'和沒有,它都有效。謝謝。 –