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

如何为DataFrame中所有现有行添加2005-2022的年份列

实现DataFrame每行对应2005-2022所有年份的方法

完全可以实现,以下是两种简洁的解决方案:

方法一:交叉连接(Cross Join)

利用pandas的merge方法配合how='cross',直接将原DataFrame的每一行与2005-2022的所有年份进行组合:

import pandas as pd

# 构建原始DataFrame
df_dict = {'country': ['Japan','Japan','Japan','Japan','Japan','Japan','Japan', 'Greece','Greece','Greece','Greece','Greece','Greece','Greece'],
           'product': ["A", "B", "C", "D", "E", "F", "G", "A", "B", "C", "D", "E", "F", "G"],
           'region': ["Asia","Asia","Asia","Asia","Asia","Asia","Asia","Europe","Europe","Europe","Europe","Europe","Europe","Europe"]}
df = pd.DataFrame(df_dict)

# 生成包含2005到2022年份的DataFrame
years_df = pd.DataFrame({'year': range(2005, 2023)})

# 执行交叉连接,得到目标结果
result_df = df.merge(years_df, how='cross')

# 按需求排序(可选)
result_df = result_df.sort_values(by=['country', 'product', 'year']).reset_index(drop=True)

方法二:利用explode展开列表

先给每行添加包含所有年份的列表,再通过explode将列表拆分为单独行:

import pandas as pd

# 构建原始DataFrame
df_dict = {'country': ['Japan','Japan','Japan','Japan','Japan','Japan','Japan', 'Greece','Greece','Greece','Greece','Greece','Greece','Greece'],
           'product': ["A", "B", "C", "D", "E", "F", "G", "A", "B", "C", "D", "E", "F", "G"],
           'region': ["Asia","Asia","Asia","Asia","Asia","Asia","Asia","Europe","Europe","Europe","Europe","Europe","Europe","Europe"]}
df = pd.DataFrame(df_dict)

# 为每行添加年份列表
df['year'] = [range(2005, 2023)] * len(df)

# 展开列表,得到每行对应单个年份的结果
result_df = df.explode('year').reset_index(drop=True)

# 转换年份为整数类型(可选)
result_df['year'] = result_df['year'].astype(int)

两种方法都能生成你需要的结果,其中方法一的how='cross'需要pandas 1.2.0及以上版本支持,兼容性更好的话可以选择方法二。

内容的提问来源于stack exchange,提问作者A.N.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:31:15