【问题标题】:Compute difference for each combination of dates for a given level计算给定级别的每个日期组合的差异
【发布时间】:2022-01-13 07:46:32
【问题描述】:

我有一个如下的数据框:

example_df = pd.DataFrame({"group_id": ["12356", "12356", "12359", "12356", "12359"], "date": ["2021-12-03", "2021-12-05", "2021-05-06", "2021-11-04", "2021-06-05"]})

我需要在date 列中找到每个组 ID 的日期差异。例如group_id=12356 有 3 个可用日期

["2021-12-03", "2021-12-05", "2021-11-04"]

我需要这些天之间的差异。这些给定日期有 3 种组合。我写的代码不能按我想要的方式工作,而且速度很慢,因为我使用的是iterrows。有没有更短更简单的方法来实现这一点?

我的代码:

%%time
date_diff_dict = {}
for index, row in example_df.iterrows():
    group_id = row.group_id
    group_id_df = example_df[example_df.group_id == group_id]
    date_diff_list = []
    for idx, rw in group_id_df.iterrows():
        if (row.order_id != rw.order_id) & (row.order_id >= rw.order_id):
            date_diff = np.abs((row.date - rw.date).days)
            print(row.date, rw.date)
            print(date_diff)
            date_diff_list.append(date_diff)
            print(date_diff_list)
    date_diff_dict[str(group_id)] = date_diff_list

此代码给出了部分正确的答案,但错过了一天。

预期输出是:

{'12356': [2, 29, 31], '12359': [30]}

【问题讨论】:

    标签: python pandas dataframe loops


    【解决方案1】:

    这是一种方法:

    (i) 将“日期”从字符串文字转换为日期时间对象

    (ii)groupby“日期”

    (iii) 对于每个组,使用 itertools.combinations 查找日期对

    (iv) 求日期对之间天数的绝对差

    from itertools import combinations
    example_df['date'] = pd.to_datetime(example_df['date'])
    out = example_df.groupby('group_id')['date'].apply(lambda date: [abs((y-x).days) for x,y in combinations(date, 2)]).to_dict()
    

    输出:

    {'12356': [2, 29, 31], '12359': [30]}
    

    【讨论】:

      猜你喜欢
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多