Skip to content
Advertisement

Error: ‘str’ object has no attribute ‘shape’ while trying to covert datetime in a dataframe

Consider a I have a column called ‘test’ of a dataframe. The column elements are like this:

201604
201605

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:

df['test'] = pd.to_datetime(df['test'].apply(lambda x: x[:4])+"-"+df['test'].apply(lambda x: x[-2:]))

Initially I have used the following code

df['test'] = pd.to_datetime(df['test'].apply(lambda x: str(x[:4]))+"-"+df['test'].apply(lambda x: 
                                                                str(x[-2:]))+"-01",format="%Y-%m-%d")

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

df=pd.DataFrame({
    'test':['201604', '201605']
})
df

Input df

test
0   201604
1   201605

Code

df.test = pd.to_datetime(df.test, format='%Y%m')
df

Output

    test
0   2016-04-01
1   2016-05-01
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement