【问题标题】:How to transform a pandas dataframe to multiindex dataframe如何将熊猫数据框转换为多索引数据框
【发布时间】:2020-02-13 06:35:36
【问题描述】:

我有时间序列 pandas 数据框,我想将其转换为具有一列的多索引数据框。

这是数据框:

Date         MMM             ABT             ABBV            ABMD
20171017    -0.004455   0.007810    0.012260    0.011132
20171018    0.002382    0.012731    0.040296    0.002775
20171019    0.004424    0.004107    0.004561    -0.00429
20171020    0.009398    0.005682    -0.003954   0.013801

我试过这段代码:

for date in returns.index:

    arrays = [[[date] * len(returns.columns)][0], 
    list(returns.columns)]
    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples)
    multi.loc[(date,np.array(index.levels[1])),:] = 
    returns.loc[date,:].values.reshape(-1,1)

但是我得到以下错误:

TypeError: unhashable type: 'numpy.ndarray'

我希望有:

                    Returns
 20171017   MMM  -0.004455
            ABT  0.007810
            ABBV     0.012260
            ABMD     0.011132
            ACN  -0.003173
            ATVI     0.002919
            ADBE     -0.000532
            AMD  -0.007062
            AAP  0.023612
            AES  -0.007149
            AMG  -0.007792
            AFL  -0.005014
            A    -0.011948
            APD  0.001629
            AKAM     -0.002966
            ALK  0.000621

【问题讨论】:

    标签: python python-3.x pandas time-series multi-index


    【解决方案1】:

    使用DataFrame.set_indexDataFrame.stack 表示Series with MultiIndex,如有必要,使用一列DataFrame 添加Series.to_frame

    df = df.set_index('Date').stack().to_frame('Returns')
    print (df)
                    Returns
    Date                   
    20171017 MMM  -0.004455
             ABT   0.007810
             ABBV  0.012260
             ABMD  0.011132
    20171018 MMM   0.002382
             ABT   0.012731
             ABBV  0.040296
             ABMD  0.002775
    20171019 MMM   0.004424
             ABT   0.004107
             ABBV  0.004561
             ABMD -0.004290
    20171020 MMM   0.009398
             ABT   0.005682
             ABBV -0.003954
             ABMD  0.013801
    

    【讨论】:

      【解决方案2】:

      使用DataFrame.set_index + DataFrame.stack。然后使用Series.rename重命名serie。最后使用to_frame转换为数据框:

      df.set_index('Date').stack().rename('returns').to_frame()
      

                      returns
      Date                   
      20171017 MMM  -0.004455
               ABT   0.007810
               ABBV  0.012260
               ABMD  0.011132
      20171018 MMM   0.002382
               ABT   0.012731
               ABBV  0.040296
               ABMD  0.002775
      20171019 MMM   0.004424
               ABT   0.004107
               ABBV  0.004561
               ABMD -0.004290
      20171020 MMM   0.009398
               ABT   0.005682
               ABBV -0.003954
               ABMD  0.013801
      

      【讨论】:

        猜你喜欢
        • 2020-05-11
        • 2019-09-28
        • 2013-12-26
        相关资源
        最近更新 更多