gpt4 book ai didi

python - 将 Pandas 日期时间月份转换为字符串表示形式

转载 作者:太空狗 更新时间:2023-10-30 01:50:37 25 4
gpt4 key购买 nike

我想要一个带有时间戳列的 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'))

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

最佳答案

使用矢量化 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

关于python - 将 Pandas 日期时间月份转换为字符串表示形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36010999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com