简体   繁体   English

根据'hour'datetime选择Pandas数据帧行

[英]Select Pandas dataframe rows based on 'hour' datetime

I have a pandas dataframe 'df' with a column 'DateTimes' of type datetime.time. 我有一个pandas数据帧'df',其列为'DateTimes',类型为datetime.time。

The entries of that column are hours of a single day: 该列的条目是一天的小时数:

00:00:00
.
.
.
23:59:00

Seconds are skipped, it counts by minutes. 秒数被跳过,按分钟计算。

How can I choose rows by hour, for example the rows between 00:00:00 and 00:01:00? 如何按小时选择行,例如00:00:00到00:01:00之间的行?


If I try this: 如果我试试这个:

df.between_time('00:00:00', '00:00:10')

I get an error that index must be a DateTimeIndex. 我得到一个错误,索引必须是DateTimeIndex。

I set the index as such with: 我将索引设置为:

df=df.set_index(keys='DateTime')

but I get the same error. 但我得到了同样的错误。

I can't seem to get 'loc' to work either. 我似乎无法让'loc'工作。 Any suggestions? 有什么建议么?

Here a working example of what you are trying to do: 这里是您尝试做的一个工作示例:

times = pd.date_range('3/6/2012 00:00', periods=100, freq='S', tz='UTC')
df = pd.DataFrame(np.random.randint(10, size=(100,1)), index=times)
df.between_time('00:00:00', '00:00:30')

Note the index has to be of type DatetimeIndex. 请注意,索引必须是DatetimeIndex类型。

I understand you have a column with your dates/times. 我知道你有一个包含日期/时间的专栏。 The problem probably is that your column is not of this type, so you have to convert it first, before setting it as index: 问题可能是您的列不属于此类型,因此您必须先将其转换,然后再将其设置为索引:

# Method A
df.set_index(pd.to_datetime(df['column_name'], drop=True)

# Method B
df.index = pd.to_datetime(df['column_name'])
df = df.drop('col', axis=1)

(The drop is only necessary if you want to remove the original column after setting it as index) (只有在将原始列设置为索引后才删除原始列时才需要删除)

Check out these links: 看看这些链接:
convert column to date type: Convert DataFrame column type from string to datetime 将列转换为日期类型: 将DataFrame列类型从字符串转换为datetime
filter dataframe on dates: Filtering Pandas DataFrames on dates 过滤日期上的数据 :在日期过滤Pandas DataFrame
Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM