如何从namedtuple实例列表创建pandas DataFrame(具有索引或多索引)? [英] How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances?
本文介绍了如何从namedtuple实例列表创建pandas DataFrame(具有索引或多索引)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单的例子:
>>> 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']
是索引本身,而不是我想用作索引的列.
Now it thinks that ['ticker', 'date']
is the index itself, rather than the columns I want to use as the index.
有没有一种方法,而不必求助于中间的numpy ndarray或事后使用set_index
?
Is there a way to do this without resorting to an intermediate numpy ndarray or using set_index
after the fact?
推荐答案
要从命名元组获取系列,可以使用_fields
属性:
To get a Series from a namedtuple you could use the _fields
attribute:
In [11]: pd.Series(a, a._fields)
Out[11]:
ticker GE
date 2010-01-01
price 30
dtype: object
类似地,您可以创建一个这样的DataFrame:
Similarly you can create a DataFrame like this:
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
这篇关于如何从namedtuple实例列表创建pandas DataFrame(具有索引或多索引)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文