从pandas数据帧的字典中检索特定列

时间:2014-10-14 16:48:56

标签: python dictionary dataframe

我有一个字典,其中包含键和pandas数据帧的字符串作为项/值。每个数据帧具有相同的列名,长度等。我想知道的是,我是否可以单独使用此结构,并将每个数据帧的第5列的所有数据作为参数传递给函数,例如PCA?

目前我正在循环遍历每个键,抓取所需的列并将其合并到一个新的数据帧中,但这看起来非常难看......

1 个答案:

答案 0 :(得分:1)

您可以使用面板。在pandas文档中有一个很好的例子:

In [109]: df = DataFrame({'a': ['foo', 'bar', 'baz'],
   .....:                 'b': np.random.randn(3)})
   .....: 

In [110]: df
Out[110]: 
     a         b
0  foo -2.006481
1  bar  0.301016
2  baz  0.059117

In [111]: data = {'item1': df, 'item2': df}

In [112]: panel = Panel.from_dict(data, orient='minor')

In [113]: panel['a']
Out[113]: 
  item1 item2
0   foo   foo
1   bar   bar
2   baz   baz

In [114]: panel['b']
Out[114]: 
      item1     item2
0 -2.006481 -2.006481
1  0.301016  0.301016
2  0.059117  0.059117