简体   繁体   中英

convert a series of strings to a series of pandas Timestamp objects

The way I am doing this looks inefficient, so I figured that there had to be a better way that I am just not seeing.

Current approach:

dates = pd.DataFrame(['2019-10-15', '2019-10-15', '2017-05-24', '2019-11-01', '2019-11-01',
     '2019-11-01', '2019-11-01', '2019-11-01', '2020-01-11', '2019-11-01'], columns=['string'])
dates['timestamp'] = [pd.Timestamp(x) for x in dates['string']]

The following code did the trick for me:

Since I am using inbuilt function and it is a vectorized operation. This would be relatively faster.

dates['timestamp'] = pd.to_datetime(dates['string'])

You can use the apply function if you don't want to use a python list comprehension

dates['timestamp'] = dates['string'].apply(pd.Timestamp)

Won't be all that much faster but is a little cleaner imo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM