如何在 pandas 数据框中移动日期(加x个月)? [英] How to shift dates in a pandas dataframe (add x months)?

查看:97
本文介绍了如何在 pandas 数据框中移动日期(加x个月)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe with columns of dates.

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

I know how to shift dates by a fixed number of months (eg add 3 months to all the dates in column x); however, I cannot figure out how to shift dates by a number of months which is not fixed, but is another column of the dataframe.

有什么想法吗?

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

I have copied a minimal example below. The error I get is:

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您可以使用应用,其中 axis = 1

IIUC you could use apply with 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]

这篇关于如何在 pandas 数据框中移动日期(加x个月)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆