熊猫合并和合并行

时间:2020-01-14 02:04:57

标签: python pandas

我的原始数据有一些列数据,我正在扩展到自己的列。它是这样开始的:

Order ID    Items    Order Line item Properties 1 Title    Order Line item Properties 1 Value
--------    -----    ----------------------------------    ----------------------------------
1           x        Org ID                                1234
2           x        Org ID                                5678
2           x        Ship From                             DEN
2           y        Ship To                               CLE
2           y        Org ID                                5678
2           y        Ship From                             DEN
2           y        Ship To                               CLE

我有一些代码可以为Org IDShip FromShip To创建列。结果数据如下:

Order ID    Items    Org ID    Ship From    Ship To
--------    -----    ------    ---------    --------
1           x        1234      None         None
2           x        5678      None         None
2           x        5678      DEN          None
2           x        5678      None         CLE
2           y        5678      None         None
2           y        5678      DEN          None
2           y        5678      None         CLE

我正在尝试使数据看起来像这样:

Order ID    Items    Org ID    Ship From    Ship To
--------    -----    ------    ---------    --------
1           x        1234      None         None
2           x, y     5678      DEN          CLE

我想我对所有事情都掌握了,除了在其余数据相同时将项目串联起来以显示为x, y为止。

以下一些代码几乎可以帮助我解决问题:

df.groupby('Order ID').apply(lambda x: x.ffill().bfill()).drop_duplicates()

我可以这样输入[str(x) for x in df['Items']],但我不确定如何将其输入到结果行的项目字段中。

对于订单2上的项目,我该怎么做才能合并,连接,压扁,联接或以x, y结尾的正确单词?

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

df.groupby(['Order ID','Org ID'])['Items'].apply(lambda x: ','.join(set(x.astype(str)))).reset_index()

输出

      Order ID  Org ID  Items
0         1     1234      x
1         2     5678    y,x

答案 1 :(得分:1)

要回答有关Arun答案的评论问题,您可以通过在groupby列表中添加列标题来添加更多列:

<div class="col-12">
                <video width="320" height="240" class="pt-3" controls preload="auto">
                    <source src="/videos/video1.MP4" type="video/mp4"> Your browser does not support the video tag.
                </video>
                <video width="320" height="240" controls class="pt-3" preload="auto">
                    <source src="/videos/video2.MOV" type="video/mp4"> Your browser does not support the video tag.
                </video>
                <video width="320" height="240" controls class="pt-3" preload="auto">
                    <source src="/videos/video3.MOV" type="video/mp4"> Your browser does not support the video tag.
                </video>
                <video width="320" height="240" controls class="pt-3" preload="auto">
                    <source src="/videos/video4.MP4" type="video/mp4"> Your browser does not support the video tag.
                </video>
            </div>
        </div>