gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:33 24 4
gpt4 key购买 nike

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

我知道如何将日期移动固定的月数(例如,将 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 你可以将 applyaxis=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]

关于python - 如何在 Pandas 数据框中移动日期(添加 x 个月)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com