Python笔记本 - 将年份和月份分成2个不同的列

时间:2017-11-13 23:26:54

标签: python jupyter-notebook

我的python笔记本中有一列名为Date。这包含了

我需要将其拆分为2列,因此一个名为Year和One MonthNo?

代码我有atm;

import calendar
from datetime import datetime

crimes['NewDate'] = crimes['Date'].apply(lambda x: datetime.strptime(x.split( [0], '%Y-%m'))

crimes['MonthNo'] = crimes['Date'].apply(lambda x: str(x.split()[0].split('-')[0]))

monthDict = {'01' : 'Jan', '02' : 'Feb', '03' : 'Mar', '04' : 'Apr', '05' : 'May', '06' : 'June', '07' : 'Jul', '08' : 'Aug', '09' : 'Sep', '10' : 'Oct', '11' : 'Nov', '12' : 'Dec' }

crimes['Month'] = crimes['MonthNo'].apply(lambda x: monthDict[x])
crimes.head()

1 个答案:

答案 0 :(得分:1)

您可以拆分连字符,然后使用日历模块直接获取月份名称或缩写。

import calendar
import pandas as pd

dates = ['2017-05','2017-04','2016-03']
crimes = pd.DataFrame()

years = [int(i.split('-')[0]) for i in dates]
months = [int(i.split('-')[1]) for i in dates]
month_names = [calendar.month_name[i] for i in months]

#Alternatively, use abbrv for abbreviation
#month_names = [calendar.month_abbr[i] for i in months]

crimes['Year'] = years
crimes['Month'] = month_names