如何从DataFrame的Date列中提取月份名称和年份 [英] How to Extract Month Name and Year from Date column of DataFrame

查看:1936
本文介绍了如何从DataFrame的Date列中提取月份名称和年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下DF

45    2018-01-01
73    2018-02-08
74    2018-02-08
75    2018-02-08
76    2018-02-08

我想以一种简单的方式以以下格式提取月份名称和年份:

I want to extract the month name and year in a simple way in the following format:

45    Jan-2018
73    Feb-2018
74    Feb-2018
75    Feb-2018
76    Feb-2018

我使用了 df.Date.dt.to_period( M) 返回 2018-01 格式。

推荐答案

将日期从对象更改为实际日期,然后使用dt访问所需的内容。

Cast you date from object to actual datetime and use dt to access what you need.

import pandas as pd

df = pd.DataFrame({'Date':['2019-01-01','2019-02-08']})

df['Date'] = pd.to_datetime(df['Date'])

# You can format your date as you wish
df['Mon_Year'] = df['Date'].dt.strftime('%b-%Y')

# the result is object/string unlike `.dt.to_period('M')` that retains datetime data type.

print(df['Mon_Year'])

这篇关于如何从DataFrame的Date列中提取月份名称和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆