【问题标题】:Input random dates into the column pandas [duplicate]将随机日期输入到熊猫列中[重复]
【发布时间】:2022-01-08 03:30:10
【问题描述】:

我有一个名为 df_planned 的数据框,想在“order_date”列中插入一些从 2021 年 10 月开始的随机日期。有没有办法在循环中做到这一点?有 300 行数据,显然日期可以重复。

我写了这个函数来生成日期:

import datetime
def new(test_date,K):
    res = [test_date + datetime.timedelta(days=idx) for idx in range(K)]
    # printing result
    return(res)

test_date = datetime.datetime(2021, 10, 1)

【问题讨论】:

    标签: python pandas dataframe datetime


    【解决方案1】:

    您可以使用np.random.choicepd.date_range

    import pandas as pd
    import numpy as np
    
    df['order_date'] = np.random.choice(pd.date_range('2021-10-01', '2021-10-31'), 300)
    print(df)
    
    # Output:
        order_date
    0   2021-10-08
    1   2021-10-27
    2   2021-10-21
    3   2021-10-11
    4   2021-10-05
    ..         ...
    295 2021-10-13
    296 2021-10-05
    297 2021-10-23
    298 2021-10-22
    299 2021-10-31
    
    [300 rows x 1 columns]
    

    注意:将 300 替换为数据帧的长度len(df)

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 2013-07-15
      • 2019-02-20
      • 2019-04-02
      • 2021-10-25
      • 2020-12-01
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多