简单示例:
>>> 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
属性:
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
关于python - 如何从 namedtuple 实例列表中创建 pandas DataFrame(带有索引或多索引)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17004985/