我有一个从Python 3.7中的数据帧中提取的熊猫系列。 它包含一系列时间码,例如:
17833 Sat, 27 Nov 2010 06:00:00 -0000
851 Fri, 04 Dec 2009 06:07:00 -0000
4806 Fri, 23 Mar 2012 06:02:15 -0000
16341 Sat, 20 Aug 2011 11:48:18 -0000
9444 Mon, 16 May 2011 08:06:53 -0000
...
3262 Fri, 16 Dec 2011 07:30:00 -0000
37554 Wed, 11 Apr 2012 02:20:34 -0000
37555 Wed, 11 Apr 2012 02:34:00 -0000
28471 Thu, 18 Feb 2010 04:46:00 -0000
30324 Thu, 28 Jun 2012 21:23:40 -0000
左边的数字是原始条目的索引。 我希望能够将此系列分类为各种替代时间格式,例如按工作日分组(将所有"星期六"分组,将所有"星期三"分组等(或按月分组("11月","五月"(。 使用此时间码信息(02 小时、06 小时等的所有条目(在 24 小时制按小时排序甚至很棒。
目标输出将是(仅对此示例进行排序(:
按月
28471 Feb
4806 Mar
37554 Apr
37555 Apr
9444 May
...
30324 Jun
16341 Aug
17833 Nov
851 Dec
3262 Dec
按工作日
9444 Mon
37554 Wed
37555 Wed
28471 Thu
30324 Thu
...
4806 Fri
851 Fri
3262 Fri
16341 Sat
17833 Sat
按时间
37554 02
37555 02
28471 04
17833 06
4806 06
...
851 06
3262 07
9444 08
16341 11
30324 21
我已经尝试使用 pd.to_datetime(( 函数,但我不确定该为该函数提供什么格式才能理解该系列,这里的澄清可能会有所帮助。
如果你想要与你发布的输出完全一样,你可以这样做,将列名视为'funded date'
:
对于月份:
s_month=pd.to_datetime(df['funded date']).dt.month_name().str[:3]
s_month.reindex(pd.to_datetime(df['funded date']).dt.month.sort_values().index)
28471 Feb
4806 Mar
37554 Apr
37555 Apr
9444 May
30324 Jun
16341 Aug
17833 Nov
851 Dec
3262 Dec
对于一天:
s_day=pd.to_datetime(df['funded date']).dt.day_name().str[:3]
s_day.reindex(pd.to_datetime(df['funded date']).dt.dayofweek.sort_values().index)
9444 Mon
37554 Wed
37555 Wed
28471 Thu
30324 Thu
851 Fri
4806 Fri
3262 Fri
17833 Sat
16341 Sat
要按星期几排序,我们可以将您的日期转换为实际日期时间格式 (datetime64
(。然后我们从日期时间中提取dayofweek
并按该数字对其进行排序:
s = pd.to_datetime(df['Col1'].str.rsplit(n=2).str[0], format='%a, %d %b %Y').dt.dayofweek
df.assign(dayofweek=s).sort_values('dayofweek').drop(columns=['dayofweek'])
输出
Col1
4 Mon, 16 May 2011 08:06:53 -0000
6 Wed, 11 Apr 2012 02:20:34 -0000
7 Wed, 11 Apr 2012 02:34:00 -0000
8 Thu, 18 Feb 2010 04:46:00 -0000
9 Thu, 28 Jun 2012 21:23:40 -0000
1 Fri, 04 Dec 2009 06:07:00 -0000
2 Fri, 23 Mar 2012 06:02:15 -0000
5 Fri, 16 Dec 2011 07:30:00 -0000
0 Sat, 27 Nov 2010 06:00:00 -0000
3 Sat, 20 Aug 2011 11:48:18 -0000
dt.dayofweek
返回一个序列,其中星期几表示为integer
:
pd.to_datetime(df['Col1'].str.rsplit(n=2).str[0], format='%a, %d %b %Y').dt.dayofweek
0 5
1 4
2 4
3 5
4 0
5 4
6 2
7 2
8 3
9 3
Name: Col1, dtype: int64
您可以对month
执行相同的操作:
s2 = pd.to_datetime(df['Col1'].str.rsplit(n=2).str[0], format='%a, %d %b %Y').dt.month
df.assign(month=s2).sort_values('month').drop(columns=['month'])
Col1
8 Thu, 18 Feb 2010 04:46:00 -0000
2 Fri, 23 Mar 2012 06:02:15 -0000
6 Wed, 11 Apr 2012 02:20:34 -0000
7 Wed, 11 Apr 2012 02:34:00 -0000
4 Mon, 16 May 2011 08:06:53 -0000
9 Thu, 28 Jun 2012 21:23:40 -0000
3 Sat, 20 Aug 2011 11:48:18 -0000
0 Sat, 27 Nov 2010 06:00:00 -0000
1 Fri, 04 Dec 2009 06:07:00 -0000
5 Fri, 16 Dec 2011 07:30:00 -0000
对于格式化,您可以pandas.to_datetime((方法或仅使用apply((方法将strftime/strptime应用于系列。稍后,您可以将 sort_values(( 方法用于预期输出的系列或数据框。
有关 to_datetime(( 请参阅此文档,有关格式设置,请参阅此页面。