Consider a I have a column called ‘test’ of a dataframe. The column elements are like this:
JavaScript
x
3
1
201604
2
201605
3
I want to make the each column elements of the dataframe as 2016-04-01. Based on this I have written a code which is working fine in spyder but when I am trying to apply it to Jupyter Notebook it is showing some error AttributeError: ‘str’ object has no attribute ‘shape’
My code is:
JavaScript
1
2
1
df['test'] = pd.to_datetime(df['test'].apply(lambda x: x[:4])+"-"+df['test'].apply(lambda x: x[-2:]))
2
Initially I have used the following code
JavaScript
1
3
1
df['test'] = pd.to_datetime(df['test'].apply(lambda x: str(x[:4]))+"-"+df['test'].apply(lambda x:
2
str(x[-2:]))+"-01",format="%Y-%m-%d")
3
In both cases it is showing error. Kindly help so that I can use it in Jupyter Notebook.
Note that dtypes is object for ‘test’.
Advertisement
Answer
We need to use format
param while converting the str to datetime
Input
JavaScript
1
5
1
df=pd.DataFrame({
2
'test':['201604', '201605']
3
})
4
df
5
Input df
JavaScript
1
4
1
test
2
0 201604
3
1 201605
4
Code
JavaScript
1
3
1
df.test = pd.to_datetime(df.test, format='%Y%m')
2
df
3
Output
JavaScript
1
4
1
test
2
0 2016-04-01
3
1 2016-05-01
4