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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:10:42  来源:igfitidea点击:

Add days to date in pandas

pythondatepandasdatetimenumpy

提问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 Datecolumn is a datetime object:

首先,确保该Date列是一个日期时间对象:

df['Date'] = pd.to_datetime(df['Date'])

Then, we can convert the Dayscolumn 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

回答by Psidom

You can convert the Days column to timedeltaand add it to Datecolumn:

您可以将 Days 列转换为timedelta并将其添加到Date列中:

import pandas as pd

df['NewDate'] = pd.to_datetime(df.Date) + pd.to_timedelta(pd.np.ceil(df.Days), unit="D")
df

enter image description here

在此处输入图片说明