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

前端 未结 1 559
粉色の甜心
粉色の甜心 2021-02-18 20:46

Simple example:

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

>>> Price = namedtuple(\'Price\', \'ticker date price\')
>         


        
相关标签:
1条回答
  • 2021-02-18 21:16

    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
    

    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
    

    You have to set_index after the fact, but you can do this 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
    
    0 讨论(0)
提交回复
热议问题