熊猫多级标题,为一行中的条目创建多行

时间:2020-06-08 15:36:37

标签: python python-3.x pandas multi-level

我有一个多层列的熊猫数据框,其中包含来自在线零售商的订单。每行都有来自单个订单的信息。这导致同一行中有多个项目。我需要为订单中出售的每个项目创建一行。因此,有数百列。

     orderID    orderinfo       orderline    orderline    orderline    orderline
     nan        orderaspect1    0            0            1            1
     nan        nan             itemaspect1  itemaspect2  itemaspect1  itemaspect2
0    1          2               3            4            5            6
1   10          20              30           40           50           60
2  100          200             300          400          500          600

在订单行下具有相同编号的每一行都需要有自己的行,其中包括来自订单iD和所有订单方面的信息。它需要看起来像这样。

     orderID    orderinfo       orderline    orderline    item #
     nan        nan             itemaspect1  itemaspect2  
0    1          2               3            4            0
1   10          20              30           40           0
2  100          200             300          400          0
3    1          2               5            6            1
4   10          20              50           60           1
5  100          200             500          600          1

这样,每个ITEM都有一行,而不是每个ORDER都有一行。 我尝试过使用熔解和堆叠来取消枢轴化,然后再进行枢轴化,但是我和多索引列都遇到了问题。没有正确格式化的格式。

[edit]
使用代码应该看起来像这样。

 i = pd.DatetimeIndex(['2011-03-31', '2011-04-01', '2011-04-04', '2011-04-05',

                   '2011-04-06', '2011-04-07', '2011-04-08', '2011-04-11',
                   '2011-04-12', '2011-04-13'])
    cols = pd.MultiIndex.from_product([['orderID', "orderlines"],['order data', 0, 1]])
    df = pd.DataFrame(np.random.randint(10, size=(len(i), 6)),index=i, columns=cols)

0 个答案:

没有答案