从形式{index:行值列表}中的字典构造Pandas DataFrame

bir*_*one 10 python dictionary list dataframe pandas

我设法使用以下方法:

dft = pd.DataFrame.from_dict({
                    0: [50, 45, 00, 00], 
                    1: [53, 48, 00, 00],
                    2: [56, 53, 00, 00],
                    3: [54, 49, 00, 00],
                    4: [53, 48, 00, 00],
                    5: [50, 45, 00, 00]
                    }, orient='index'
                    )
Run Code Online (Sandbox Code Playgroud)

完成后,构造函数看起来就像DataFrame一样,易于阅读/编辑:

>>> dft
    0   1   2   3
0   50  45  0   0
1   53  48  0   0
2   56  53  0   0
3   54  49  0   0
4   53  48  0   0
5   50  45  0   0
Run Code Online (Sandbox Code Playgroud)

DataFrame.from_dict构造函数没有columns参数,因此为列提供合理的名称需要额外的步骤:

dft.columns = ['A', 'B', 'C', 'D']
Run Code Online (Sandbox Code Playgroud)

对于这种方便(例如用于单元测试)初始化DataFrames的方式来说,这似乎很笨拙.

所以我想知道:有更好的方法吗?

Ale*_*ley 9

或者,您可以使用DataFrame.from_items()从字典构造DataFrame; 这允许您同时传入列名.

例如,如果d是你的字典:

d = {0: [50, 45, 0, 0],
     1: [53, 48, 0, 0],
     2: [56, 53, 0, 0],
     3: [54, 49, 0, 0],
     4: [53, 48, 0, 0],
     5: [50, 45, 0, 0]}
Run Code Online (Sandbox Code Playgroud)

数据是d.items(),而东方又是'index'.字典键成为索引值:

>>> pd.DataFrame.from_items(d.items(), 
                            orient='index', 
                            columns=['A','B','C','D'])
    A   B  C  D
0  50  45  0  0
1  53  48  0  0
2  56  53  0  0
3  54  49  0  0
4  53  48  0  0
5  50  45  0  0
Run Code Online (Sandbox Code Playgroud)

在Python 2中,您可以使用它d.iteritems()来生成字典的内容,以避免在内存中创建另一个列表.


gra*_*per 5

一种方法是:

df = pd.DataFrame.from_dict({
0: {"A":50, "B":40},
1: {"A":51, "B":30}}, orient='index')
Run Code Online (Sandbox Code Playgroud)

但是,为了快速测试初始化​​,我可能更喜欢你的方式+然后设置列.