【问题标题】:One-to-Many Merge on 2+ Columns Pandas在 2+ 列 Pandas 上进行一对多合并
【发布时间】:2022-01-06 01:19:53
【问题描述】:

我正在尝试合并 2 列以防止重复。从this question,我可以像这样为一列做到这一点:

df = df.groupby(['Date', 'Ticket ID', 'Score', 'many other Columns...'])['Work Order'].apply(', '.join).reset_index()

这给了我一个很好的输出:

Date                        Ticket ID           Work Order
2018-08-30 22:52:25         1444008             119846184
2021-09-29 13:33:49         1724734             122445397, 122441551

现在,我至少还有一个专栏也想做同样的事情,同时保持工单正确。但是,为不同的列重复该过程/代码似乎会删除原始列或不会像我想要的那样聚合列。我要:

Date                        Ticket ID           Work Order Num             Work Order ID
2018-08-30 22:52:25         1444008             119846184                  A6zH
2021-09-29 13:33:49         1724734             122445397, 122441551       H43a1, JU8a

我用reset_indexmerge 函数尝试了一些不同的东西,但似乎无法让它做我想做的事。这似乎应该很简单 - 我错过了什么?很有可能我也必须为其他列执行此操作,所以我想要一个可重复的解决方案。

# tried some df1 and df2 stuff - along with different locations of reset index.
df = df.groupby(['Reported Date', 'Site','Ticket ID', 'TicketUID', 'Work Order UID', \
                         'cols...'])['Work Order'].apply(', '.join)
        
df = df.groupby(['Reported Date', 'Site','Ticket ID', 'TicketUID', 'Work Order', \
                             'cols...'])['Work Order UID'].apply(', '.join)
        
# tried on='Ticket ID' here as well.
#df = pd.merge(df1, df2)

【问题讨论】:

  • 好吧,我认为您可以创建一个变量grp = df.groupby(['Date', 'Ticket ID', 'Score', 'many other Columns...']),然后每次在grp 上创建一个apply(', '.join),而不是之前操作的结果。最后你可以连接结果。

标签: python pandas dataframe


【解决方案1】:

applyDataFrameGroupBy(多个分组列)和SeriesGroupBy(单个分组列)上的工作方式不同。对于单列,它适用于元素,对于多列,它将函数应用于每一列。

所以做你想做的事情的一种方法是简单地申请两次 - f.e.:

data = {'id':[3763058, 3763058, 3763058, 3763077, 3763077, 3763078], 
        'id2':[3763056, 3763056, 3763056, 3763074, 3763074, 3763073], 
        'item1' : ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'],
        'item2' : ['itemA', 'itemB', 'itemC', 'itemD', 'itemE', 'itemF']}

df = pd.DataFrame(data)

df.groupby(['id', 'id2'])[['item1', 'item2']]\
        .apply(lambda x: x.apply(', '.join))
        .reset_index()

这给了我们结果:

    id      id2     item1               item2
0   3763058 3763056 item1, item2, item3 itemA, itemB, itemC
1   3763077 3763074 item4, item5        itemD, itemE
2   3763078 3763073 item6               itemF

【讨论】:

  • 嗯,不知道我在这个上缺少什么。我不断收到一个关键错误,并且使用df = df.groupby(['Document ID', 'many more cols'])[['Work Order', 'Work Order UID']].apply(lambda x: x.apply(', '.join))df = df.groupby(['Document ID'])[['Work Order', 'Work Order UID']].apply(lambda x: x.apply(', '.join)) 删除了我的所有其他列。打印列仅显示左侧的工单和工单 ID
  • 您能否在出现错误的地方添加一些示例数据(可能会被模拟)?
  • 另外,Work OrderWork Order UID 都不应该在 groupby 中(在 "many more cols" 中)
  • reset_index 知道了
猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 2021-05-28
  • 2022-07-21
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
相关资源
最近更新 更多