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

Python中将DataFrame转换为适配神经网络的TimeSeries Array求助

解决方案

步骤1:导入依赖库

import pandas as pd
import xarray as xr
import numpy as np

步骤2:预处理原始DataFrame

先处理日期格式并清理缺失值(神经网络无法直接处理NaN,需根据业务场景选择填充方式):

# 把Date列转为datetime64[ns]类型
df['Date'] = pd.to_datetime(df['Date'])

# 提取月度时间戳(取每月第一天,保持datetime64[ns]格式)
df['Month'] = df['Date'].dt.to_period('M').dt.to_timestamp()

# 处理NaN值,以下是几种常用方案:
# 方案1:向前填充
df['Change'] = df['Change'].ffill()
# 方案2:用对应月份的均值填充
# monthly_means = df.groupby('Month')['Change'].transform('mean')
# df['Change'] = df['Change'].fillna(monthly_means)
# 方案3:删除含NaN的行
# df = df.dropna(subset=['Change'])

步骤3:聚合为月度数据

将每日数据聚合为月度粒度(这里以均值为例,可替换为求和、中位数等):

# 按月份分组聚合
monthly_df = df.groupby('Month')['Change'].mean().reset_index()
# 确保数据按时间顺序排列
monthly_df = monthly_df.sort_values('Month')

步骤4:转换为目标维度的DataArray

根据多时间序列模型的需求,构造Month(datetime64[ns])、component、sample三维结构,以下提供两种常见场景的实现:

场景A:按年份划分样本(每个样本对应一整年的月度数据)

# 提取年份作为样本标识
monthly_df['sample'] = monthly_df['Month'].dt.year

# 重塑数据为「样本×月份」的二维结构
pivot_df = monthly_df.pivot(index='sample', columns='Month', values='Change')

# 转换为DataArray并调整维度顺序为 Month → component → sample
da = xr.DataArray(
    data=pivot_df.values[:, np.newaxis, :],  # 新增component维度
    dims=['sample', 'component', 'Month'],
    coords={
        'sample': pivot_df.index,
        'component': ['Change'],
        'Month': pivot_df.columns  # 保持datetime64[ns]类型
    }
).transpose('Month', 'component', 'sample')

场景B:滑动窗口样本(每个样本为连续N个月的数据,适配时序预测任务)

window_size = 3  # 自定义窗口大小,比如取连续3个月为一个样本
samples = []

# 生成滑动窗口样本
for i in range(len(monthly_df) - window_size + 1):
    sample_data = monthly_df.iloc[i:i+window_size]['Change'].values
    samples.append(sample_data)

# 转换为DataArray并调整维度顺序
da = xr.DataArray(
    data=np.array(samples)[:, np.newaxis, :].transpose(2, 1, 0),
    dims=['Month', 'component', 'sample'],
    coords={
        'Month': monthly_df['Month'].iloc[:window_size].values,  # 窗口内的月度时间戳
        'component': ['Change'],
        'sample': np.arange(len(samples))
    }
)

验证结果

检查最终DataArray的维度和类型是否符合要求:

print(da.dims)  # 输出: ('Month', 'component', 'sample')
print(da['Month'].dtype)  # 输出: datetime64[ns]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:35:24