Mark Graph
Mark Graph

Reputation: 5121

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']]

Upvotes: 1

Views: 334

Answers (2)

oreopot
oreopot

Reputation: 3450

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'])

Upvotes: 2

Milan
Milan

Reputation: 344

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

Upvotes: 0

Related Questions