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

如何将表达式形式的时间列转换为实际日期以构建动态时间序列?

动态时间序列转换解决方案

假设你已经通过pd.merge得到了包含option、start_year和time列的合并DataFrame,接下来只需两步就能把t-n这类表达式转换为实际年份:

步骤1:提取时间偏移量

从time列的字符串中提取相对于起始年份的偏移数值,比如把t-3转为-3,t转为0:

import pandas as pd

# 假设合并后的DataFrame名为merged_df
merged_df['offset'] = merged_df['time'].str.replace('t', '').astype(int)

如果你的time列还包含t+1这类正向偏移,这段代码同样适用,t+1会被转为1。

步骤2:计算实际年份

将起始年份与偏移量相加,得到对应的实际年份:

merged_df['actual_year'] = merged_df['start_year'] + merged_df['offset']

完整示例

以下是包含初始数据的完整代码,方便你直接测试:

# 示例初始数据
df1 = pd.DataFrame({
    'option': ['A', 'A', 'A', 'B', 'B', 'B'],
    'time': ['t-3', 't-2', 't-1', 't-2', 't-1', 't']
})

df2 = pd.DataFrame({
    'option': ['A', 'B'],
    'start_year': [2020, 2025]
})

# 合并DataFrame(你已完成的步骤)
merged_df = pd.merge(df1, df2, on='option')

# 提取偏移量并计算实际年份
merged_df['offset'] = merged_df['time'].str.replace('t', '').astype(int)
merged_df['actual_year'] = merged_df['start_year'] + merged_df['offset']

# 整理成最终的时间序列表(可选移除中间列)
final_time_series = merged_df[['option', 'time', 'actual_year']].sort_values(by=['option', 'actual_year'])
print(final_time_series)

运行后会得到如下结果:

option  time  actual_year
0      A  t-3          2017
1      A  t-2          2018
2      A  t-1          2019
3      B  t-2          2023
4      B  t-1          2024
5      B    t          2025

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:25:41