pandas 在熊猫中添加日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42768649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add days to date in pandas
提问by datascana
I have a data frame that contains 2 columns, one is Date and other is float number. I would like to add those 2 to get the following:
我有一个包含 2 列的数据框,一个是日期,另一个是浮点数。我想添加这两个以获得以下内容:
Index Date Days NewDate
0 20-04-2016 5 25-04-2016
1 16-03-2015 3.7 20-03-2015
As you can see if there is decimal it is converted as int as 3.1--> 4 (days). I have some weird questions so I appreciate any help. Thank you !
如您所见,如果有十进制,它会被转换为 int 为 3.1--> 4(天)。我有一些奇怪的问题,所以我很感激任何帮助。谢谢 !
回答by languitar
First, ensure that the Date
column is a datetime object:
首先,确保该Date
列是一个日期时间对象:
df['Date'] = pd.to_datetime(df['Date'])
Then, we can convert the Days
column to int by ceiling it and the converting it to a pandas Timedelta:
然后,我们可以将Days
列转换为 int 并将其转换为 Pandas Timedelta:
temp = df['Days'].apply(np.ceil).apply(lambda x: pd.Timedelta(x, unit='D'))
Datetime objects and timedeltas can be added:
可以添加日期时间对象和时间增量:
df['NewDate'] = df['Date'] + temp