Answer a question

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.

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

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐