将 pandas 日期时间月份转换为字符串表示 [英] Convert pandas datetime month to string representation

查看:85
本文介绍了将 pandas 日期时间月份转换为字符串表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有时间戳列的 Pandas DataFrame,并且想要创建一个只有月份的列.我想让月份列带有月份的字符串表示形式,而不是整数.我做过这样的事情:

I want to have a pandas DataFrame with a timestamp column and want to create a column with just the month. I want to have the month column with string representations of the month, not with integers. I have done something like this:

df['Dates'] = pd.to_datetime(df['Dates'])
df['Month'] = df.Dates.dt.month
df['Month'] = df.Month.apply(lambda x: datetime.strptime(str(x), '%m').strftime('%b'))

然而,这是一种蛮力方法,性能不高.有没有更优雅的方法将月份的整数表示转换为字符串表示?

However, this is some kind of a brute force approach and not very performant. Is there a more elegant way to convert the integer representation of the month into a string representation?

推荐答案

使用矢量化dt.strftime 在您的日期时间:

use vectorised dt.strftime on your datetimes:

In [43]:
df = pd.DataFrame({'dates':pd.date_range(dt.datetime(2016,1,1), dt.datetime(2017,2,1), freq='M')})
df

Out[43]:
        dates
0  2016-01-31
1  2016-02-29
2  2016-03-31
3  2016-04-30
4  2016-05-31
5  2016-06-30
6  2016-07-31
7  2016-08-31
8  2016-09-30
9  2016-10-31
10 2016-11-30
11 2016-12-31
12 2017-01-31

In [44]:    
df['month'] = df['dates'].dt.strftime('%b')
df

Out[44]:
        dates month
0  2016-01-31   Jan
1  2016-02-29   Feb
2  2016-03-31   Mar
3  2016-04-30   Apr
4  2016-05-31   May
5  2016-06-30   Jun
6  2016-07-31   Jul
7  2016-08-31   Aug
8  2016-09-30   Sep
9  2016-10-31   Oct
10 2016-11-30   Nov
11 2016-12-31   Dec
12 2017-01-31   Jan

这篇关于将 pandas 日期时间月份转换为字符串表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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