繁体   English   中英

如何从namedtuple实例列表创建pandas DataFrame(带索引或多索引)?

[英]How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances?

简单的例子:

>>> from collections import namedtuple
>>> import pandas

>>> Price = namedtuple('Price', 'ticker date price')
>>> a = Price('GE', '2010-01-01', 30.00)
>>> b = Price('GE', '2010-01-02', 31.00)
>>> l = [a, b]
>>> df = pandas.DataFrame.from_records(l, index='ticker')
Traceback (most recent call last)
...
KeyError: 'ticker'

更难的例子:

>>> df2 = pandas.DataFrame.from_records(l, index=['ticker', 'date'])
>>> df2

         0           1   2
ticker  GE  2010-01-01  30
date    GE  2010-01-02  31

现在它认为['ticker', 'date']是索引本身,而不是我想用作索引的列。

有没有办法做到这一点,而不是诉诸中间numpy ndarray或事后使用set_index

要从_fields获取Series,您可以使用_fields属性:

In [11]: pd.Series(a, a._fields)
Out[11]:
ticker            GE
date      2010-01-01
price             30
dtype: object

同样,您可以像这样创建一个DataFrame:

In [12]: df = pd.DataFrame(l, columns=l[0]._fields)

In [13]: df
Out[13]:
  ticker        date  price
0     GE  2010-01-01     30
1     GE  2010-01-02     31

你必须set_index事实后,但你可以做到这一点inplace

In [14]: df.set_index(['ticker', 'date'], inplace=True)

In [15]: df
Out[15]:
                   price
ticker date
GE     2010-01-01     30
       2010-01-02     31

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM