【问题标题】:Pandas flatten Hierarchical Multi-indexPandas 扁平化分层多索引
【发布时间】:2021-02-03 22:49:33
【问题描述】:

在尝试展平后,我有一个如下熊猫数据框:

df = pd.DataFrame(web.DataReader(stocks, 'yahoo', day, day).iloc[0]).unstack(level=0).droplevel(level=0, axis=1)

Attributes     adjClose        close  ...       volume       date
Symbols                               ...                        
FB           261.399994   261.399994  ...   13587000.0 2020-10-19
AAPL         115.980003   115.980003  ...  120639300.0 2020-10-19
AMZN        3207.209961  3207.209961  ...    5223600.0 2020-10-19
GOOG        1534.609985  1534.609985  ...    1607100.0 2020-10-19
NFLX                NaN          NaN  ...          NaN 2020-10-19

我正在尝试将其保存到数据库中;但是,我在 df.columns 中看不到符号。 为了将df保存为以下格式:

Symbols       adjClose        close  ...       volume       date 
FB           261.399994   261.399994  ...   13587000.0 2020-10-19
AAPL         115.980003   115.980003  ...  120639300.0 2020-10-19
AMZN        3207.209961  3207.209961  ...    5223600.0 2020-10-19
GOOG        1534.609985  1534.609985  ...    1607100.0 2020-10-19
NFLX                NaN          NaN  ...          NaN 2020-10-19

关于如何实现这一目标的任何建议?我的数据库在符号、日期列上有一个复合键。 谢谢。

【问题讨论】:

    标签: python pandas dataframe hierarchical


    【解决方案1】:

    符号是您的数据帧索引,您需要使用reset_index 将其放入帧本身。试试这个:

    df = (pd.DataFrame(web.DataReader(stocks, 'yahoo', day, day)
          .iloc[0])
          .unstack(level=0)
          .droplevel(level=0, axis=1)
          .rename_axis(columns=None) # Gets rid of the "Attributes"
          .reset_index()             # Puts "Symbols" as an actual column, not as the index
    )
    

    我的 2 个补充:

    • rename_axis 这应该去掉你的“属性”标题。这主要用于打印时的视觉目的,但可能会让不习惯使用多索引数据的人望而却步。本质上,您的列标签存储在 Index 对象中。这个Index 对象可以有一个名称,因此“属性”是您的列的名称(非常奇怪的概念,这对于普通索引不是超级有用-但在使用MultiIndex 时有很多用处)。
    • reset_index() 看来您的“符号”列实际上不是列(这就是为什么它没有出现在 df.columns 中,而是出现在数据框的索引中。添加此方法将插入“符号”索引作为列到数据帧中,并创建一个新索引,它是一个简单的RangeIndex,范围从 0 到数据帧的长度。

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2018-05-14
      • 1970-01-01
      • 2018-11-07
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      相关资源
      最近更新 更多