首页 > 解决方案 > Python通过复制日期索引将列合并为一列

问题描述

我想通过添加具有相同索引的行将列合并为一列。当然,索引是日期。然后我想绘制seaborn情节。

我的数据:

df = 
              A    B    # A, B two unique groups, denote 36, 24 size
timestamp                       
2019-10-01   10   20
2019-10-02   30   40

预期答案:

df = 
            val    group   size    # A, B denote 36, 24 size
timestamp                       
2019-10-01   10    A       34
2019-10-01   20    B       24
2019-10-02   30    A       34
2019-10-02   40    B       24

我的代码:

我不知道如何在这里进行。

标签: pythonpandasdataframedatetime

解决方案


尝试melt

out = df.reset_index().melt('timestamp')
Out[73]: 
    timestamp variable  value
0  2019-10-01        A     10
1  2019-10-02        A     30
2  2019-10-01        B     20
3  2019-10-02        B     40

推荐阅读