【问题标题】:how to use dataframe between_time() function如何使用数据帧 between_time() 函数
【发布时间】:2014-08-25 22:33:36
【问题描述】:

我正在尝试使用between_time 函数。我已将字符串类型时间格式化为日期时间

dataset['TimeStamp'] = pd.to_datetime(dataset['TimeStamp'],format)

我定义了搜索开始时间和结束时间:

start = datetime.time(9,40,0)

end = datetime.time(10,00,0)

然后我打电话给dataset['TimeStamp'].between_time(start, end)

这是我得到的错误:

TypeError: Index must be DatetimeIndex

请问我该如何解决。谢谢

【问题讨论】:

  • 那么您的索引是否像错误提示的那样是日期时间索引?
  • 我不知道,如何检查?我需要为数据框创建索引吗?
  • Dataframes 总是有一个索引,你可以通过type(df.index) 来检查类型,如果你从未设置过它很可能是一个 int64 自动生成的
  • 我读取这样的数据:dataset = pd.read_csv('date.txt',header=0,delimiter=' '),我应该添加什么?我看到有一个索引属性,但我不知道如何使用它。谢谢
  • 在这种情况下,pandas 会自动生成它,您可以在加载数据后随时设置它,所以在您的情况下 dataset.set_index(keys='TimeStamp',inplace=True) 应该可以工作

标签: python datetime pandas


【解决方案1】:

示例 - 我使用来自 cmets 的信息:

import pandas as pd
import StringIO
import datetime

data = '''time --- value
1984-12-12 14:08:00 --- 1
1984-12-12 14:25:00 --- 2
1984-12-12 14:47:00 --- 4
1984-12-12 16:37:00 --- 3
1984-12-12 16:37:00 --- 9
1984-12-12 16:37:00 --- 5
1984-12-12 17:52:00 --- 3
1984-12-12 17:52:00 --- 7
1984-12-12 19:29:00 --- 2'''

#------------------------------------------------

df = pd.read_csv(StringIO.StringIO(data), sep=' --- ')

df['time'] = pd.DatetimeIndex(df['time'])

print "\nDataFrame:\n", df 

print '\nIndex:', type(df.index)

#------------------------------------------------

df.set_index(keys='time', inplace=True)

print "\nDataFrame:\n", df 

print '\nIndex:', type(df.index)

#------------------------------------------------

start = datetime.time(14,50,0)
end = datetime.time(18,0,0)

print "\nResult:\n", df['value'].between_time(start, end)

结果:

DataFrame:
                 time  value
0 1984-12-12 14:08:00      1
1 1984-12-12 14:25:00      2
2 1984-12-12 14:47:00      4
3 1984-12-12 16:37:00      3
4 1984-12-12 16:37:00      9
5 1984-12-12 16:37:00      5
6 1984-12-12 17:52:00      3
7 1984-12-12 17:52:00      7
8 1984-12-12 19:29:00      2

Index: <class 'pandas.core.index.Int64Index'>

DataFrame:
                     value
time                      
1984-12-12 14:08:00      1
1984-12-12 14:25:00      2
1984-12-12 14:47:00      4
1984-12-12 16:37:00      3
1984-12-12 16:37:00      9
1984-12-12 16:37:00      5
1984-12-12 17:52:00      3
1984-12-12 17:52:00      7
1984-12-12 19:29:00      2

Index: <class 'pandas.tseries.index.DatetimeIndex'>

Result:
time
1984-12-12 16:37:00    3
1984-12-12 16:37:00    9
1984-12-12 16:37:00    5
1984-12-12 17:52:00    3
1984-12-12 17:52:00    7
Name: value, dtype: int64

【讨论】:

  • 对我来说这有一些奇怪的错误,我有一个带有“时间”列的数据框,我已将其转换为 datetime64[ns] 列,使用您的代码,指定开始(1990-01- 01) 和结束 (1990-12-31) 日期,它返回日期为 1957-09-02 的行?我的数据框中的日期涵盖了 20 世纪(1900 年到 1999 年)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2020-10-02
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
相关资源
最近更新 更多