2013-09-25 75 views
10

尋找一種快速的方法,將熊貓數據框中的一行變爲有序的字典,無需使用列表。列表很好,但大型數據集需要很長時間。我正在使用fiona GIS閱讀器,並且行的順序與給出數據類型的模式一致。我使用熊貓來加入數據。在很多情況下,這些行會有不同的類型,所以我想用一個字符串類型轉換成一個numpy數組可能會有訣竅。如何快速將熊貓數據幀行變爲ordereddict

回答

16

不幸的是,你不能只是做一個應用(因爲它適合回一個數據幀):

In [1]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) 

In [2]: df 
Out[2]: 
    a b 
0 1 2 
1 3 4 

In [3]: from collections import OrderedDict 

In [4]: df.apply(OrderedDict) 
Out[4]: 
    a b 
0 1 2 
1 3 4 

但是你可以用與iterrows列表理解:

In [5]: [OrderedDict(row) for i, row in df.iterrows()] 
Out[5]: [OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 3), ('b', 4)])] 

如果有可能使用發電機,而不是清單,無論你正在使用什麼,這通常會更高效:

In [6]: (OrderedDict(row) for i, row in df.iterrows()) 
Out[6]: <generator object <genexpr> at 0x10466da50> 
4

這在pandas 0.21.0+實現在功能上與to_dict參數into

df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) 
print (df) 
    a b 
0 1 2 
1 3 4 

d = df.to_dict(into=OrderedDict, orient='index') 
print (d) 
OrderedDict([(0, OrderedDict([('a', 1), ('b', 2)])), (1, OrderedDict([('a', 3), ('b', 4)]))])