【问题标题】:Sorting data frame by time period; datetime64[ns]按时间段对数据帧进行排序;日期时间64[ns]
【发布时间】:2022-01-08 04:29:20
【问题描述】:

我在总结一列时遇到了另一个问题 (Python - 熊猫)

我有一个“新”数据框,其日期为 5 天。 “日期”列是 datetime64[ns] 类型。 我尝试按日期过滤数据框,例如“2021-10-10 和 2021-10-15 之间的所有值”或“2021-10-14 之后的所有值”等。 无论我尝试什么,我都会收到错误消息。 开始于:

mask = (new['Date'] > '2021-10-10') & (df['Date'] <= '2021-10-15')

我明白了:

TypeError: '<=' not supported between instances of 'date time.date' and 'str'

出现此错误后,我尝试按照建议转换切片 “问题是您想使用字符串 '2017-07-07' 进行切片,而您的索引类型为 date time.date。您的切片也应该属于这种类型。 您可以通过如下定义开始日期和结束日期来做到这一点:

import pandas as pd
startdate = pd. to_datetime("2017-7-7").date()
enddate = pd. to_datetime("2017-7-10").date()
df.loc[startdate:enddate]

(我当然删除了空格) 但现在我明白了

TypeError: '<' not supported between instances of 'int' and 'date time.date'

我只想按不同的时间段对我的数据框进行排序和过滤。 感谢您的帮助

【问题讨论】:

  • 这与“总结十进制数”有什么关系?
  • 对不起,那是个错误!我会改的。

标签: python pandas numpy date time


【解决方案1】:

为了确保所有内容都采用相同的格式,请使用 pd.to_datetime() 并使用 infer_datetime_format=True 有助于格式化并加快功能:

df['Date'] = pd.to_datetime(df['Date'],infer_datetime_format=True)

df = df[(df['Date'] > pd.to_datetime('2021-10-10')) & (df['Date'] <= pd.to_datetime('2021-10-15'))]

【讨论】:

  • 谢谢 Celius,现在可以使用了
  • 我现在如何设置startdate = pd. to_datetime("2017-7-7").date()enddate = pd. to_datetime("2017-7-10").date()?它给出了错误: AttributeError: 'str' object has no attribute 'date'
  • 使用 .dt.date 代替 .date()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 2016-02-01
  • 2021-04-05
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多