【问题标题】:pandas create a new column of item pairs熊猫创建一个新的项目对列
【发布时间】:2021-06-13 23:13:16
【问题描述】:

我有一个这样的数据框:

orderID Product PurchaseDate
123 A 08/05/2021
123 B 08/05/2021
123 C 08/05/2021
123 D 08/05/2021
245 B 11/05/2021
245 C 11/05/2021
245 A 11/05/2021
... ... ...

我想创建一列产品对,因此我的新 df 将是:

orderID ProductPairs PurchaseDate
123 A,B 08/05/2021
123 B,C 08/05/2021
123 C,D 08/05/2021
123 A,C 08/05/2021
123 B,D 08/05/2021
... ... ...

知道如何用 pandas 做到这一点吗?

【问题讨论】:

  • 您能解释一下如何对产品进行分组吗?分组 A,B 的逻辑是什么?将具有相同 orderID 的产品分组?如果你想对具有相同 orderID 的产品进行分组,你想对日期做什么?
  • 是的,我想根据 orderID 对购买的产品对(单独购买)进行分组,并计算它们之间的平均间隔。
  • 请编辑您的问题以包含更多解释 - 为什么 D 得到 08/05/2021?
  • 也有点不清楚为什么 245 没有出现在输出中。您想要每个 orderID 单独的帧吗?还有什么?
  • 此表是一个示例,有超过 2 个订单 ID 和超过 4 个产品,但不,我不想要分离的数据帧,多合一。我希望现在一切都清楚了。

标签: python pandas data-science


【解决方案1】:

IIUC 试试groupby agg + itertools.combinations + explode:

from itertools import combinations

new_df = (
    df.groupby(['orderID', 'PurchaseDate'])['Product']
        .agg(lambda p: list(combinations(p, 2)))
        .explode()
        .str.join(',')
        .reset_index(name='ProductPairs')
)

new_df:

   orderID PurchaseDate ProductPairs
0      123   08/05/2021          A,B
1      123   08/05/2021          A,C
2      123   08/05/2021          A,D
3      123   08/05/2021          B,C
4      123   08/05/2021          B,D
5      123   08/05/2021          C,D
6      245   11/05/2021          B,C
7      245   11/05/2021          B,A
8      245   11/05/2021          C,A

【讨论】:

    猜你喜欢
    • 2023-02-05
    • 1970-01-01
    • 2021-12-30
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    相关资源
    最近更新 更多