简体   繁体   中英

New column transforming date into month-year pandas python

I would like to create a new column which will show the month-year based on another column where the date can be found.

I have created the following code:

BusinessObjects_na_['Customer Handover Date'] = pd.to_datetime(BusinessObjects_na_['Customer Handover Date'])
BusinessObjects_na_['Month'] = BusinessObjects_na_['Customer Handover Date'].apply(lambda x: str(x).strftime('%B-%Y'))

However Python gives the following error:

AttributeError: 'str' object has no attribute 'strftime'

Can someone help me with this one?

if you're running a recent version of pandas you can use dt.strftime :

BusinessObjects_na_['Month'] = BusinessObjects_na_['Customer Handover Date'].dt.strftime('%B-%Y')

Your code would've worked without the cast to `str:

BusinessObjects_na_['Month'] = BusinessObjects_na_['Customer Handover Date'].apply(lambda x: x.strftime('%B-%Y'))

Example:

In [276]:
df = pd.DataFrame({'date':pd.date_range(dt.datetime(2016,1,1), periods=10)})
df

Out[276]:
        date
0 2016-01-01
1 2016-01-02
2 2016-01-03
3 2016-01-04
4 2016-01-05
5 2016-01-06
6 2016-01-07
7 2016-01-08
8 2016-01-09
9 2016-01-10

In [279]:    
df['date'].dt.strftime('%b-%Y')

Out[279]:
0    Jan-2016
1    Jan-2016
2    Jan-2016
3    Jan-2016
4    Jan-2016
5    Jan-2016
6    Jan-2016
7    Jan-2016
8    Jan-2016
9    Jan-2016
Name: date, dtype: object

and

In [281]:
df['date'].apply(lambda x: x.strftime('%b-%Y'))

Out[281]:
0    Jan-2016
1    Jan-2016
2    Jan-2016
3    Jan-2016
4    Jan-2016
5    Jan-2016
6    Jan-2016
7    Jan-2016
8    Jan-2016
9    Jan-2016
Name: date, dtype: object

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