'Stack()'输出,所有Individual索引都填充在Pandas DataFrame中

时间:2016-10-19 16:12:42

标签: python pandas dataframe data-munging

我有以下DataFrame:

import pandas as pd
import numpy as np
dates = pd.date_range('20130101',periods=6)
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))

是:

out[]:df
                A          B            C           D
2013-01-01  0.849638    0.163683    -0.422279   -0.981363
2013-01-02  -0.828562   -0.726762   -0.154431   1.695164
2013-01-03  1.668989    1.057559    -0.958682   -1.443136
2013-01-04  -3.386432   0.115499    -2.095343   -1.887334
2013-01-05  1.595712    0.270327    -0.532860   -0.690501
2013-01-06  -1.734169   0.574431    -0.982097   1.092113

我有目的地堆叠数据框,如下所示:

2013-01-01  A    0.849638
            B    0.163683
            C   -0.422279
            D   -0.981363
2013-01-02  A   -0.828562
            B   -0.726762
            C   -0.154431
            D    1.695164
2013-01-03  A    1.668989
            B    1.057559
            C   -0.958682
            D   -1.443136
2013-01-04  A   -3.386432
            B    0.115499
            C   -2.095343
            D   -1.887334
2013-01-05  A    1.595712
            B    0.270327
            C   -0.532860
            D   -0.690501
2013-01-06  A   -1.734169
            B    0.574431
            C   -0.982097
            D    1.092113
dtype: float64

我希望在所有行中打印日期而不是合并在一起。我想要这样的东西:

2013-01-01  A    0.849638
2013-01-01  B    0.163683
2013-01-01  C   -0.422279
2013-01-01  D   -0.981363
.......
.......

2013-01-06  A   -1.734169
2013-01-06  B    0.574431
2013-01-06  C   -0.982097
2013-01-06  D    1.092113

dtype: float64

任何人都可以帮助我实现这一目标。谢谢。

1 个答案:

答案 0 :(得分:2)

相关的pandas选项为'display.multi_sparse'
你可以自己设置

pd.set_option('display.multi_sparse', False)

或使用pd.option_context暂时将其设置为with

with pd.option_context('display.multi_sparse', False):
    dates = pd.date_range('20130101',periods=6)
    print(pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD')).stack())

2013-01-01  A    0.074056
2013-01-01  B    0.565971
2013-01-01  C    0.312375
2013-01-01  D    0.000926
2013-01-02  A    0.669702
2013-01-02  B    0.458241
2013-01-02  C    0.854965
2013-01-02  D    1.608542
2013-01-03  A    0.358990
2013-01-03  B    0.194446
2013-01-03  C   -0.988489
2013-01-03  D   -0.967467
2013-01-04  A   -0.768605
2013-01-04  B    0.791746
2013-01-04  C    0.073552
2013-01-04  D   -0.604505
2013-01-05  A    0.254031
2013-01-05  B    0.143891
2013-01-05  C   -0.351159
2013-01-05  D    0.642623
2013-01-06  A    0.499416
2013-01-06  B   -0.588694
2013-01-06  C    1.418078
2013-01-06  D   -0.071737
dtype: float64