You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python&Pandas:如何生成特定格式的日期伪数据列

生成指定格式的日期伪数据列

实现思路

先构造2010.01到2020.12之间所有合法的年月浮点值,再通过随机采样为20万行DataFrame分配对应值,确保最终列的dtype为float。

代码实现

方法一:直接计算年月浮点值

import pandas as pd
import numpy as np

# 生成2010.01至2020.12的所有年月浮点值
year_month_values = []
for year in range(2010, 2021):
    for month in range(1, 13):
        year_month_values.append(year + month / 100)

# 为20万行生成随机采样数据
df = pd.DataFrame()  # 替换为你的现有DataFrame
df['date_col'] = np.random.choice(year_month_values, size=200000, replace=True)

# 验证数据类型
print(df['date_col'].dtype)  # 输出应为float64

方法二:利用Pandas日期序列转换

import pandas as pd
import numpy as np

# 生成按月度的日期序列
monthly_dates = pd.date_range(start='2010-01-01', end='2020-12-31', freq='MS')
# 转换为年.月格式的浮点值
date_float_values = monthly_dates.year + monthly_dates.month / 100

# 随机采样并添加到DataFrame
df = pd.DataFrame()  # 替换为你的现有DataFrame
df['date_col'] = np.random.choice(date_float_values, size=200000, replace=True)

关键说明

  • 两种方法生成的数值均严格匹配年.月格式(如2010.01、2020.12),且dtype为float64,符合需求。
  • np.random.choice的replace=True参数允许重复取值,满足随机分配的场景。
  • 20万行数据的生成效率极高,不会出现性能瓶颈。

内容的提问来源于stack exchange,提问作者Fable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:40:39