小编Key*_*hsh的帖子

如何将 pandas 数据框转换为多索引数据框

我有时间序列 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
Run Code Online (Sandbox Code Playgroud)

我尝试了这段代码:

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)
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

TypeError: unhashable type: 'numpy.ndarray'
Run Code Online (Sandbox Code Playgroud)

我期望有:

                    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 …
Run Code Online (Sandbox Code Playgroud)

python time-series multi-index python-3.x pandas

3
推荐指数
1
解决办法
3816
查看次数

标签 统计

multi-index ×1

pandas ×1

python ×1

python-3.x ×1

time-series ×1