Pandas - 将一列中的秒数添加到另一列中的日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46081457/
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
Pandas - Add seconds from a column to datetime in other column
提问by RolandDeschain
I have a dataFrame with two columns, ["StartDate" ,"duration"]
the elements in the StartDate
column are datetime
type, and the duration
are ints.
我有一个包含两列的数据框,列中["StartDate" ,"duration"]
的元素StartDate
是datetime
类型,duration
是整数。
Something like:
就像是:
StartDate Duration
08:16:05 20
07:16:01 20
I expect to get:
我希望得到:
EndDate
08:16:25
07:16:21
Simply add the seconds to the hour.
只需将秒添加到小时即可。
I'd being checking some ideas about it like the delta time typesand that all those datetimes have the possibilities to add delta times, but so far I can find how to do it with the DataFrames (in a vector fashion, cause It might be possible to iterate over all the rows performing the operation ).
我正在检查一些关于它的想法,比如增量时间类型,并且所有这些日期时间都有可能添加增量时间,但到目前为止我可以找到如何使用 DataFrames(以矢量方式,因为它可能是可以迭代执行操作的所有行)。
回答by Vaishali
consider this df
考虑这个 df
StartDate duration
0 01/01/2017 135
1 01/02/2017 235
You can get the datetime column like this
您可以像这样获取日期时间列
df['EndDate'] = pd.to_datetime(df['StartDate']) + pd.to_timedelta(df['duration'], unit='s')
df.drop('StartDate,'duration', axis = 1, inplace = True)
You get
你得到
EndDate
0 2017-01-01 00:02:15
1 2017-01-02 00:03:55
EDIT: with the sample dataframe that you posted
编辑:使用您发布的示例数据框
df['EndDate'] = pd.to_timedelta(df['StartDate']) + pd.to_timedelta(df['Duration'], unit='s')
回答by A.Kot
df.StartDate = df.apply(lambda x: pd.to_datetime(x.StartDate)+pd.Timedelta(Second(df.duration)) ,axis = 1)