2014-09-12 54 views
5

如何用兩個或多個含有共同鍵的詞典創建熊貓DataFrame?也就是說,爲了將同名鍵詞典加入到熊貓數據框中

d1 = {'a': 1} 
d2 = {'a': 3} 
... 

轉換成一個數據幀與由相應的字典確定列['d1', 'd2', ...],索引等"a"和值的行?

+0

這個問題已經被要求在這裏:http://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – 2014-09-12 17:55:01

+0

@ColonelBeauvel呃,我想只有當你眯起眼睛,除非你意外地鏈接了錯誤的問題 – Ajean 2014-09-12 19:26:42

+0

@Ajean字典本來可以用一些隨機數命名爲d45,d34,..等等。在這種情況下,下面的答案不起作用。鏈接中的作者強調了這一棘手的問題:「我想從這個列表中創建一個Pandas中的DataFrame,其中列名由實際字典的名稱給出」 – 2014-09-12 19:29:17

回答

4
import pandas as pd 
d1 = {'a': 1, 'b':2} 
d2 = {'a': 3, 'b':5} 

df = pd.DataFrame([d1, d2]).T 
df.columns = ['d{}'.format(i) for i, col in enumerate(df, 1)] 

產生

In [40]: df 
Out[40]: 
    d1 d2 
a 1 3 
b 2 5