简体   繁体   中英

pandas transform string into datetype

I have a dataframe with string data as follows:

import pandas as pd
mydates = {'a':'2008-04-11','b':'2007-06-14','c':'2001-01-08','d':'2001-07-31'}
myDF = pd.DataFrame.from_dict(mydates,orient='index', columns=['dates'])

I am playing around with data to get the a column where the dates are real type dates.
The question here is why one the first one of the following two methods work. I would expect exactly the same result with both.
One works, the other one does not work.
(note1: I create help and help2 columns applying the string methods i consider appropriate and then create two columns as_date1 based on help1 and as_date2 based on help2 column)
(note2: the replacement -00 by -01 is due to the fact that the system created dates of the shape 2018-01-00 which does not exist and day 1 is assigned)

# transform into date: 
# the following two lines work
myDF['help']=myDF['dates'].astype('str').apply(lambda x: x.replace('-00','-01')).apply(lambda x: x.replace('-',''))
myDF['as_date1'] = pd.to_datetime(myDF['help'], format='%Y%m%d')

# the follwoing line does not show error but...
myDF['help2']=myDF['dates'].astype('str').str.replace('-00','-01').replace('-','')
# ...the following line does not work:
# ERROR: myDF['as_date2'] = pd.to_datetime(myDF['help2'], format='%Y%m%d')
# The error comes from the fact that in the column help2 the hyphens were not deleted
myDF

Why are columns help1 and help2 not equal, or in other words why the replaces of the second transformation with simply.replace and no.apply function do not work?

thanks

Just change this line:

myDF['help2']=myDF['dates'].astype('str').str.replace('-00','-01').replace('-','')

to:

myDF['help2']=myDF['dates'].astype('str').str.replace('-00','-01').str.replace('-','')

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