创建随机日期时间列,条件是另一个日期时间列 pandas
问题内容
我有一个 pandas 数据框 df_sample:
columna columnba aaa abb bab bbb bc
我已经创建了一个随机列,其中包含一些日期对象:
df_sample['contract_starts'] = np.random.choice(pd.date_range('2024-01-01', '2024-05-01'), len(df_sample))
这会导致以下输出:
columna columnb contract_startsa aa 2024-01-21a ab 2024-03-03b ba 2024-01-18b bb 2024-02-18b bc 2024-04-03
如何创建另一个日期时间列contract_noted,该值也有给定范围(例如直到 2024-05-01 )但不超过 contract_startscolumn,例如:
columnA columnB contract_starts contract_notedA AA 2024-01-21 2024-01-20A AB 2024-03-03 2024-01-01B BA 2024-01-18 2024-01-13B BB 2024-02-18 2024-02-01B BC 2024-04-03 2024-03-28
正确答案
您可以通过 从 contract_starts 列中减去随机时间增量numpy.random.randint 与 to_timedelta:
df_sample['contract_noted'] = (df_sample['contract_starts'] - pd.to_timedelta(np.random.randint(1,30, len(df_sample)), unit='d'))print (df_sample) columna columnb contract_starts contract_noted0 a aa 2024-04-18 2024-03-211 a ab 2024-02-12 2024-01-222 b ba 2024-02-21 2024-02-023 b bb 2024-04-12 2024-03-294 b bc 2024-02-10 2024-02-03
如果还需要开始和结束之间的日期时间,如 contract_starts 生成 1 之间的 inetegers 以及与开始日期时间的差异:
days =(df_sample['contract_starts'] - pd.Timestamp('2024-01-01')).dt.daysprint (days)df_sample['contract_noted'] = (df_sample['contract_starts'] - pd.to_timedelta(np.random.randint(1,days, len(df_sample)), unit='d'))print (df_sample) columnA columnB contract_starts contract_noted0 A AA 2024-02-09 2024-01-091 A AB 2024-04-26 2024-02-232 B BA 2024-04-10 2024-04-063 B BB 2024-01-31 2024-01-074 B BC 2024-01-14 2024-01-08