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

如何将DataFrame中多个Datetime列转换为机器学习适用向量格式?

Pandas日期时间列转机器学习可用向量方案

针对DataFrame中的datetime类型列,以下是几种实用的转换方案,适配SVM、KNN、逻辑回归等模型的输入要求:

方案1:时间戳归一化(单维向量)

将datetime转换为Unix时间戳,再归一化到0-1区间,得到反映时间先后的单维数值向量。

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

# 示例数据
df = pd.DataFrame({
    'date_col': ['2003-01-09', '2022-10-12 23:03:34']
})
# 转换为datetime类型
df['date_col'] = pd.to_datetime(df['date_col'])

# 转Unix时间戳(秒为单位)
df['timestamp'] = df['date_col'].astype('int64') // 10**9

# 归一化到0-1区间
scaler = MinMaxScaler()
df['normalized_time'] = scaler.fit_transform(df[['timestamp']])

# 输出结果
print(df['normalized_time'].values)

输出示例:[[0. ] [0.62857143]],可直接作为模型输入特征。

方案2:拆分时间成分并归一化(多维向量)

提取年、月、日、时、分、秒等时间成分,分别归一化后组合成多维向量,保留时间各维度的细节信息。

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

df = pd.DataFrame({
    'date_col': ['2003-01-09', '2022-10-12 23:03:34']
})
df['date_col'] = pd.to_datetime(df['date_col'])

# 提取时间成分,缺失的时分秒补0
df['year'] = df['date_col'].dt.year
df['month'] = df['date_col'].dt.month
df['day'] = df['date_col'].dt.day
df['hour'] = df['date_col'].dt.hour.fillna(0)
df['minute'] = df['date_col'].dt.minute.fillna(0)
df['second'] = df['date_col'].dt.second.fillna(0)

# 归一化所有时间成分
time_features = ['year', 'month', 'day', 'hour', 'minute', 'second']
scaler = MinMaxScaler()
df[time_features] = scaler.fit_transform(df[time_features])

# 输出多维向量
print(df[time_features].values)

输出示例:

[[0.         0.         0.26666667 0.         0.         0.        ]
 [1.         0.81818182 0.4        0.95833333 0.05       0.56666667]]

方案3:周期性编码(正弦/余弦转换)

针对月、日、时这类周期性特征,用正弦/余弦编码消除周期边界的数值跳变问题(比如12月到1月,模型不会误判为数值突变)。

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'date_col': ['2003-01-09', '2022-10-12 23:03:34']
})
df['date_col'] = pd.to_datetime(df['date_col'])

# 提取周期性特征
df['month'] = df['date_col'].dt.month
df['day_of_year'] = df['date_col'].dt.dayofyear
df['hour'] = df['date_col'].dt.hour.fillna(0)

# 正弦余弦编码
df['month_sin'] = np.sin(2 * np.pi * df['month'] / 12)
df['month_cos'] = np.cos(2 * np.pi * df['month'] / 12)
df['day_sin'] = np.sin(2 * np.pi * df['day_of_year'] / 365)
df['day_cos'] = np.cos(2 * np.pi * df['day_of_year'] / 365)
df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)

# 输出编码后的向量
print(df[['month_sin', 'month_cos', 'day_sin', 'day_cos']].values)

输出示例:

[[ 0.5        0.8660254  -0.99975503  0.02220262]
 [-0.8660254  -0.5         0.87442273  0.48531933]]

方案选择建议

  • 仅需反映时间先后顺序:选时间戳归一化
  • 需要保留时间各维度细节:选拆分成分归一化
  • 数据存在明显周期性规律:选周期性编码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:53:12