按一天中的小时排序熊猫数据

时间:2018-11-30 12:13:14

标签: python pandas sorting

给出以下数据集,这些数据集是我通过Panda从Excel文件中提取的:

enter image description here

[131124 rows x 2 columns]

date               datetime64[ns]
places_occupees             int64
dtype: object

是否有一种方法可以按一天中的小时对数据进行排序,而不管日期如何?

例如,我想在早上9点至10点之间获取所有数据。

您可以在下面找到数据集的样本。

https://ufile.io/jlilr

1 个答案:

答案 0 :(得分:0)

转换为日期时间pd.to_datetime(df['date'])后,您可以创建一个包含小时的单独列,例如df['Hour'] = df.date.dt.hour,然后按其排序 df.sort_values('Hour')

编辑:

由于要按时间排序,而不是使用小时,请将时间戳部分放入“时间”列。为了获得9到10之间的时间,您可以按小时== 9进行过滤,然后按以下时间列进行排序

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

#put the timestamp part of the datetime into a separate column
df['time'] = df['date'].dt.time

#filter by times between 9 and 10 and sort by timestamp
df.loc[df.date.dt.hour==9].sort_values('time')
相关问题