【问题标题】:to_datetime - max function returns the wrong max dateto_datetime - max 函数返回错误的最大日期
【发布时间】:2021-11-22 04:12:36
【问题描述】:

我有来自 csv 文件的数据,我正在尝试获取最大日期。

数据:

0    01/01/1994
1    01/01/1994
2    01/01/1994
3    01/01/1994
4    01/01/1994
.
.
.
970075    31/08/2021
970076    31/08/2021
970077    31/08/2021
970078    31/08/2021
970079    31/08/2021

但是,我得到了错误的最大值。似乎我的代码将我的日期列设置为字符串,而不是日期格式,即使我设置了 to_datetime。因此,我在该字符串上使用re 来获取年份。

我的代码:

file['Date'] = pd.to_datetime(file['Date'], errors = 'coerce',
                dayfirst = True, format = '%d.%m.%Y'
                ).dt.strftime('%d/%m/%Y')


print(file['Date'].min(), file['Date'].max(), range(int(re.search(r'(\d{4})', file['Date'].min()).group()), int(re.search(r'(\d{4})', file['Date'].max()).group())))

返回:

01/01/1994 31/12/2020 range(1994, 2020)

我想获得最大值 31/08/2021 而不是 31/12/2020

【问题讨论】:

  • 我觉得你是在比较字符串而不是日期,当然还有'31/12...' > '31/08...'

标签: python pandas string


【解决方案1】:

删除 .dt.strftime 用于将日期时间转换为字符串 repr。

.dt.strftime('%d/%m/%Y')

minmax之后可以转换为自定义格式。

所有在一起,也简化以获得最大和最小年份:

file['Date'] = pd.to_datetime(file['Date'], errors = 'coerce', dayfirst = True)
years = file['Date'].dt.year

print(file['Date'].min().strftime('%d/%m/%Y'), 
      file['Date'].max().strftime('%d/%m/%Y'), 
      range(years.min(), years.max()))

01/01/1994 31/08/2021 range(1994, 2021)

【讨论】:

  • 有效!!但是在那之后,我做了一个:for yearX in range(years.min(), years.max()): include_data = file[years == yearX] print(yearX),它返回 2020 作为最后一年......为什么?
  • @SultryT。 - 需要for yearX in range(years.min(), years.max() + 1),如果检查例如this,不包含停止值
  • 嗯,好的!这不是因为dt.year 配置。我的愚蠢错误,谢谢。
猜你喜欢
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2016-09-12
相关资源
最近更新 更多