在 Pandas 中将整数系列转换为 timedelta [英] Convert integer series to timedelta in pandas
问题描述
我在 Pandas 中有一个数据框,其中包含事件发生后的天数.我想创建一个新列,通过从当前日期中减去天数来计算事件的日期.每次我尝试应用 pd.offsets.Day
或 pd.Timedelta
时,我都会收到一个错误,指出 Series 是不受支持的类型.当我使用 apply
时也会发生这种情况.当我使用 map
时,我收到一个运行时错误,提示调用 Python 对象时超出了最大递归深度".
I have a data frame in pandas which includes number of days since an event occurred. I want to create a new column that calculates the date of the event by subtracting the number of days from the current date. Every time I attempt to apply pd.offsets.Day
or pd.Timedelta
I get an error stating that Series are an unsupported type. This also occurs when I use apply
. When I use map
I receive a runtime error saying "maximum recursion depth exceeded while calling a Python object".
例如,假设我的数据框如下所示:
For example, assume my data frame looked like this:
index days_since_event
0 5
1 7
2 3
3 6
4 0
我想用事件的日期创建一个新列,所以我的预期结果(使用今天的日期 12/29/2015)
I want to create a new column with the date of the event, so my expected outcome (using today's date of 12/29/2015)
index days_since_event event_date
0 5 2015-12-24
1 7 2015-12-22
2 3 2015-12-26
3 6 2015-12-23
4 0 2015-12-29
我尝试了多种方法来执行此操作,但每种方法都收到了错误.
I have attempted multiple ways to do this, but have received errors for each.
我尝试过的一种方法是:
One method I tried was:
now = pd.datetime.date(pd.datetime.now())
df['event_date'] = now - df.days_since_event.apply(pd.offsets.Day)
因此,我收到一条错误消息,指出系列是不受支持的类型.
With this I received an error saying that Series are an unsupported type.
我使用 .map
而不是 .apply
尝试了上述操作,并收到了 调用 Python 对象时超出最大递归深度"的错误em>.
I tried the above with .map
instead of .apply
, and received the error that "maximum recursion depth exceeded while calling a Python object".
我也尝试将天数转换为时间增量,例如:
I also attempted to convert the days into timedelta, such as:
df.days_since_event = (dt.timedelta(days = df.days_since_event)).apply
这也收到了一个错误,指出该系列是不受支持的类型.
This also received an error referencing the series being an unsupported type.
推荐答案
首先,要将带有整数的列转换为 timedelta,可以使用 to_timedelta
:
First, to convert the column with integers to a timedelta, you can use to_timedelta
:
In [60]: pd.to_timedelta(df['days_since_event'], unit='D')
Out[60]:
0 5 days
1 7 days
2 3 days
3 6 days
4 0 days
Name: days_since_event, dtype: timedelta64[ns]
然后您可以使用当前日期创建一个新列并减去这些时间增量:
Then you can create a new column with the current date and substract those timedelta's:
In [62]: df['event_date'] = pd.Timestamp('2015-12-29')
In [63]: df['event_date'] = df['event_date'] - pd.to_timedelta(df['days_since_event'], unit='D')
In [64]: df['event_date']
Out[64]:
0 2015-12-24
1 2015-12-22
2 2015-12-26
3 2015-12-23
4 2015-12-29
dtype: datetime64[ns]
这篇关于在 Pandas 中将整数系列转换为 timedelta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!