Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp object has no attribute dt

I am trying to convert a new column in a dataframe through a function based on the values in the date column, but get an error indicating "Timestamp object has no attribute dt." However, if I run this outside of a function, the dt attribute works fine.

Any guidance would be appreciated.

This code runs with no issues:

sample = {'Date': ['2015-07-02 11:47:00', '2015-08-02 11:30:00']}
dftest = pd.DataFrame.from_dict(sample)
dftest['Date'] = pd.to_datetime(dftest['Date'])
display(dftest.info())
dftest['year'] = dftest['Date'].dt.year
dftest['month'] = dftest['Date'].dt.month

This code gives me the error message:

sample = {'Date': ['2015-07-02 11:47:00', '2015-08-02 11:30:00']}
dftest = pd.DataFrame.from_dict(sample)
dftest['Date'] = pd.to_datetime(dftest['Date'])
def CALLYMD(dftest):
    if dftest['Date'].dt.month>9:
        return str(dftest['Date'].dt.year) + '1231'
    elif dftest['Date'].dt.month>6: 
        return str(dftest['Date'].dt.year) + '0930'
    elif dftest['Date'].dt.month>3: 
        return str(dftest['Date'].dt.year) + '0630'
    else:
        return str(dftest['Date'].dt.year) + '0331'
    

dftest['CALLYMD'] = dftest.apply(CALLYMD, axis=1)

Lastly, I'm open to any suggestions on how to make this code better as I'm still learning.

like image 699
Shawn Schreier Avatar asked Jul 08 '20 21:07

Shawn Schreier


Video Answer


1 Answers

I'm guessing you should remove .dt in the second case. When you do apply it's applying to each element, .dt is needed when it's a group of data, if it's only one element you don't need .dt otherwise it will raise {AttributeError: 'Timestamp' object has no attribute 'dt'}

reference: https://stackoverflow.com/a/48967889/13720936

like image 52
Jerry wu Avatar answered Sep 19 '22 13:09

Jerry wu