Skip to main content
 首页 » 编程设计

python之如何在 Pandas 数据框中移动日期(添加 x 个月)

2025年05月04日11TianFang

我有一个包含日期列的数据框。

我知道如何将日期移动固定的月数(例如,将 3 个月添加到 x 列中的所有日期);但是,我无法弄清楚如何将日期移动数月,这不是固定的,而是数据框的另一列。

有什么想法吗?

我在下面复制了一个最小的例子。我得到的错误是:

The truth value of a Series is ambiguous 

非常感谢!

import pandas as pd 
import numpy as np 
import datetime 
 
df = pd.DataFrame() 
df['year'] = np.arange(2000,2010) 
df['month'] = 3 
 
df['mydate'] = pd.to_datetime(  (df.year * 10000 + df.month * 100 +1).apply(str), format='%Y%m%d') 
df['month shift'] = np.arange(0,10) 
 
# if I want to shift mydate by 3 months, I can convert it to DatetimeIndex and use dateOffset: 
df['my date shifted by 3 months'] = pd.DatetimeIndex( df['mydate'] ) + pd.DateOffset(months = 3) 
 
# however, how do I shift mydate by the number of months in the column 'month shift'? 
#This does NOT work: 
df['my date shifted'] = pd.DatetimeIndex( df['mydate'] ) + pd.DateOffset(months = df['month shift']) 
print df 

请您参考如下方法:

IIUC 你可以将 apply 与 axis=1 一起使用:

In [23]: df.apply(lambda x: x['mydate'] + pd.DateOffset(months = x['month shift']), axis=1) 
Out[23]: 
0   2000-03-01 
1   2001-04-01 
2   2002-05-01 
3   2003-06-01 
4   2004-07-01 
5   2005-08-01 
6   2006-09-01 
7   2007-10-01 
8   2008-11-01 
9   2009-12-01 
dtype: datetime64[ns]