Python:在数据框中按小时选择行

我在 csv 文件中有以下数据框,我想选择与当前小时对应的所有行。


time,values


2018-10-28 08:16:49.469508,48


2018-10-28 08:16:54.471987,48


2018-10-28 08:16:59.475236,48


2018-10-28 08:17:04.478681,48

下面是我正在尝试的功能 current = datetime.datetime.now()


start = datetime.datetime(current.year,current.month,current.day,current.hour,0)


end = datetime.datetime(current.year,current.month,current.day,current.hour,59)


df = pd.io.parsers.read_csv('water_data1.csv', parse_dates=[0], index_col=0)


print(df.query('start < time < end'))

我收到以下错误


pandas.core.computation.ops.UndefinedVariableError:未定义名称“开始”


有人可以建议什么是实现这一目标的正确语法。谢谢赫曼斯


弑天下
浏览 193回答 2
2回答

白衣染霜花

pd.DataFrame.query需要在外部变量前面加上@:df = pd.DataFrame({'A': list(range(10))})start, end = 3, 6print(df.query('@start < A < @end'))&nbsp; &nbsp;A4&nbsp; 45&nbsp; 5您还可以使用pd.Series.between:res = df[df['A'].between(start, end, inclusive=False)]最后,在处理datetime值时,您应该更喜欢pd.Timestamp常规的 Python 类型:now = pd.Timestamp('now')start = now.replace(second=0, microsecond=0)end = now.replace(second=59, microsecond=0)print((start, end))(Timestamp('2018-11-01 17:36:00'), Timestamp('2018-11-01 17:36:59'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python