简体   繁体   中英

Python Dataframe: Extract Date from Datetime field — 'Not Callable' Error

Updated Follow-up Question:

Error received after running code below: UnboundLocalError: local variable 'month_name' referenced before assignment

在此处输入图片说明

I have an object column that I converted into datetime successfully called "dtin". Below is what the data looks like:

在此处输入图片说明

I want to create a new column that extracts out just the month from the dtin column (see screen shot).

Below is the code I tried and the resulting error:

在此处输入图片说明

Any help is greatly appreciated.

As per my comment above, you need to remove the () like so.

df_EVENT4_6['start_month'] = df_EVENT4_6['dtin'].dt.month

This is because 'month' is not a function or method but a property. The () is trying to call something that can't be called.

There are a number of ways you could change to the month name. I would probably define a function and use the apply method.

def month_change(mnum):
    if mnum == 1:
        mname='Jan'
    elif .....
    return(mname)      

 df_EVENT4_6['dtin']=df_EVENT4_6['dtin'].apply(month_change)

UPDATE

My bad, you need to apply it to the other Series.

def month_change(mnum):
    if mnum == 1:
        mname='Jan'
    elif .....
    return(mname)

 df_EVENT4_6['start_month'] = df_EVENT4_6['dtin'].dt.month

 df_EVENT4_6['start_month']=df_EVENT4_6['start_month'].apply(month_change)

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