2016-10-28 65 views
0

我想創建一個新的列,它將顯示基於另一列的日期可以找到的月份年。新列轉化爲月份年份熊貓python

我已經創建了下面的代碼:

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')) 

但是Python中提供了以下錯誤:

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

有人能幫助我嗎?

+0

你有沒有嘗試刪除轉換爲'str'? 'lambda x:x.strftime('%B-%Y')' – Ben

回答

5

如果你正在運行一個最近的大熊貓的版本,你可以使用dt.strftime

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

您的代碼會一直沒有投合作`STR:

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

例子:

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