解决思路:
- 将
df1和df2中的'时间'列提取出年月(即year和month),并创建新的列来进行匹配。 - 使用
merge操作将df1和df2根据年月匹配并将变量1加入到df1中。
实现步骤:
- 提取年月:可以使用
pd.to_datetime提取年份和月份。 - 匹配数据:将
df1和df2根据提取的年月进行合并。
import pandas as pd
# 假设 df1 和 df2 已经存在,且 df1 中有时间列,df2 中有时间和变量1列
# 创建示例数据
df1 = pd.DataFrame({
'时间': ['2025-05-01 00:00:00', '2025-06-01 00:00:00', '2025-05-10 00:00:00'],
'其他数据': [10, 20, 30]
})
df2 = pd.DataFrame({
'时间': ['2025-05-01 00:00:00', '2025-06-01 00:00:00'],
'变量1': [100, 200]
})
# 将 '时间' 列转换为 datetime 类型
df1['时间'] = pd.to_datetime(df1['时间'])
df2['时间'] = pd.to_datetime(df2['时间'])
# 提取年份和月份
df1['year_month'] = df1['时间'].dt.to_period('M') # 年月
df2['year_month'] = df2['时间'].dt.to_period('M') # 年月
# 合并 df1 和 df2,基于 'year_month' 进行匹配
df1 = pd.merge(df1, df2[['year_month', '变量1']], on='year_month', how='left')
# 查看结果
print(df1)
输出结果将是:
时间 其他数据 year_month 变量1
0 2025-05-01 00:00:00 10 2025-05 100.0
1 2025-06-01 00:00:00 20 2025-06 200.0
2 2025-05-10 00:00:00 30 2025-05 100.0
8742

被折叠的 条评论
为什么被折叠?



