简单的例子:
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 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html事后,但你可以这样做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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)