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

标签 python pandas

简单示例:

>>> 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/

相关文章:

python - 根据多列的值向数据框添加新列

python - 将 Scipy 与 Pandas 一起使用的警告

python - 如何在 Python 中按名称引用整数

python - 在 python 中轮询 api 以获取特定的 json 元素

python - Numpy int 位长

python - 从 pandas 数据帧着色时间序列数据

python - 当多线程 python 进程运行时,操作系统开始杀死进程

python - Blender UV 纹理图像未使用 Python API 更新

pandas - 通过使用新的多索引重复一行来创建 pandas 数据框

python - Dask 相当于 pandas.DataFrame.update