我有一个包含日期的专栏。我想要一个包含Year-Week的专栏,例如:2018-13
。
此处13表示04.01.2018
的一年中的第13周。
你能帮我解决一下这段话吗?
输入日期样本:
0 04.01.2018
1 04.01.2018
2 04.01.2018
3 04.01.2018
4 05.01.2018
帖子Convert a column of timestamps into periods in pandas无法同时提取年份和星期。
答案 0 :(得分:-1)
我假设您使用的是pandas
。
将您的系列转换为datetime
,然后使用datetime
/ pd.Series.apply
str.format
个对象的功能:
df['date'] = pd.to_datetime(df['date'])
df['y-m'] = df['date'].apply(lambda x: '{0}-{1}'.format(x.year, x.isocalendar()[1]))
# date y-m
# 0 2018-04-01 2018-13
# 1 2018-04-01 2018-13
# 2 2018-04-01 2018-13
# 3 2018-04-01 2018-13
# 4 2018-05-01 2018-18