python - how to apply ceiling to pandas DateTime -
suppose have pandas dataframe column values datetime64[ns]
.
out[204]: 0 2015-03-20 00:00:28 1 2015-03-20 00:01:44 2 2015-03-20 00:02:55 3 2015-03-20 00:03:39 4 2015-03-20 00:04:32 5 2015-03-20 00:05:52 6 2015-03-20 00:06:36 7 2015-03-20 00:07:44 8 2015-03-20 00:08:56 9 2015-03-20 00:09:47 name: datetime, dtype: datetime64[ns]
is there easy way convert them nearest minute after time? i.e. want following:
out[204]: 0 2015-03-20 00:01:00 1 2015-03-20 00:02:00 2 2015-03-20 00:03:00 3 2015-03-20 00:04:00 4 2015-03-20 00:05:00 5 2015-03-20 00:06:00 6 2015-03-20 00:07:00 7 2015-03-20 00:08:00 8 2015-03-20 00:09:00 9 2015-03-20 00:10:00 name: datetime, dtype: datetime64[ns]
i wrote complicate code first converts them string , extracts 3 portions of 00:09:47
, convert them integers, unless last portion (seconds) 00
, make last portion (seconds) 00
, adds 1
middle portion (minutes) except if middle portion (minutes) 59
in case adds first portion (hours). recombine new integers string , reconstruct datetime
.
but thinking may there might existing simpler solution. have suggestions?
* edit *
@jeff, @unutbu, answers. can select 1 answer in so, both work.
given dataframe column of dtype datetime64[ns]
, use
df['date'] += np.array(-df['date'].dt.second % 60, dtype='<m8[s]')
to add appropriate number of seconds obtain ceiling.
for example,
import io import sys import numpy np import pandas pd stringio = io.bytesio if sys.version < '3' else io.stringio df = '''\ 2015-03-20 00:00:00 2015-03-20 00:00:28 2015-03-20 00:01:44 2015-03-20 00:02:55 2015-03-20 00:03:39 2015-03-20 00:04:32 2015-03-20 00:05:52 2015-03-20 00:06:36 2015-03-20 00:07:44 2015-03-20 00:08:56 2015-03-20 00:09:47''' df = pd.read_table(stringio(df), sep='\s{2,}', header=none, parse_dates=[0], names=['date']) df['date'] += np.array(-df['date'].dt.second % 60, dtype='<m8[s]') print(df)
yields
date 0 2015-03-20 00:00:00 1 2015-03-20 00:01:00 2 2015-03-20 00:02:00 3 2015-03-20 00:03:00 4 2015-03-20 00:04:00 5 2015-03-20 00:05:00 6 2015-03-20 00:06:00 7 2015-03-20 00:07:00 8 2015-03-20 00:08:00 9 2015-03-20 00:09:00 10 2015-03-20 00:10:00
Comments
Post a Comment