pandas 将熊猫日期时间月份转换为字符串表示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36010999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:52:27  来源:igfitidea点击:

Convert pandas datetime month to string representation

pythonpandaspython-datetime

提问by farnold

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:

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

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?

但是,这是某种蛮力方法,并且性能不高。有没有更优雅的方法将月份的整数表示形式转换为字符串表示形式?

回答by EdChum

use vectorised dt.strftimeon your datetimes:

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

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

回答by jezrael

For versions pandas 0.23.0+is possible use dt.month_name:

对于版本pandas 0.23.0+可以使用dt.month_name

df['month'] = df['dates'].dt.month_name()
print (df)

        dates      month
0  2016-01-31    January
1  2016-02-29   February
2  2016-03-31      March
3  2016-04-30      April
4  2016-05-31        May
5  2016-06-30       June
6  2016-07-31       July
7  2016-08-31     August
8  2016-09-30  September
9  2016-10-31    October
10 2016-11-30   November
11 2016-12-31   December
12 2017-01-31    January