我有一個 pandas 資料框 df_sample:
columna columnb a aa a ab b ba b bb b bc
我已經建立了一個隨機列,其中包含一些日期物件:
df_sample['contract_starts'] = np.random.choice(pd.date_range('2024-01-01', '2024-05-01'), len(df_sample))
這會導致以下輸出:
columna columnb contract_starts a aa 2024-01-21 a ab 2024-03-03 b ba 2024-01-18 b bb 2024-02-18 b bc 2024-04-03
如何建立另一個日期時間列contract_noted,該值也有給定範圍(例如直到 2024-05-01 )但不超過 contract_starts
column,例如:
columnA columnB contract_starts contract_noted A AA 2024-01-21 2024-01-20 A AB 2024-03-03 2024-01-01 B BA 2024-01-18 2024-01-13 B BB 2024-02-18 2024-02-01 B BC 2024-04-03 2024-03-28
您可以透過 從contract_starts
列中減去隨機時間增量numpy.random. randint
與to_timedelta
< /a>:
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_noted 0 a aa 2024-04-18 2024-03-21 1 a ab 2024-02-12 2024-01-22 2 b ba 2024-02-21 2024-02-02 3 b bb 2024-04-12 2024-03-29 4 b bc 2024-02-10 2024-02-03
如果還需要開始與結束之間的日期時間,如 contract_starts
產生 1
之間的 inetegers 以及與開始日期時間的差異:
days =(df_sample['contract_starts'] - pd.Timestamp('2024-01-01')).dt.days print (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_noted 0 A AA 2024-02-09 2024-01-09 1 A AB 2024-04-26 2024-02-23 2 B BA 2024-04-10 2024-04-06 3 B BB 2024-01-31 2024-01-07 4 B BC 2024-01-14 2024-01-08
以上是建立隨機日期時間列,條件是另一個日期時間列 pandas的詳細內容。更多資訊請關注PHP中文網其他相關文章!