为什么 pandas strftime 引发 FutureWarning 以及如何避免它?

Why pandas strftime raises a FutureWarning and how to avoid it?

我需要将日期列解析为字符串,它有效,但我遇到了一些问题,首先是没有将字符串数据类型作为输出:

import pandas as pd  # No warning raised
exit_format = '%d-%m-%Y'
series = pd.Series([1,2,None] ,dtype='datetime64[ns]')
series.dt.strftime(exit_format)

这(预期的行为)不是什么大问题,因为可以用 astype('string') 并替换 Nan 来修复它。但最糟糕的是,如果所有值都是 NaN-Nat,我会得到这个 FutureWarning:

# Warning raised!
series = pd.Series([None,None,None] ,dtype='datetime64[ns]')
series.dt.strftime(exit_format)

FutureWarning: In a future version, the Index constructor will not infer numeric dtypes when passed object-dtype sequences (matching Series behavior)

这似乎来自 known issue pandas 版本 >= 1.4.0(我的是“1.4.1”)。我的问题是,我怎样才能做出一个好的解决方法?当所有值都是 Nan 时,为什么首先出现此警告?最好我正在寻找一个不直接抑制警告但他的来源的解决方案。

基本上,我正在寻找一个将日期列转换为字符串列但将 NaN 解析为空字符串或以更好的方式处理错误(例如使用默认值)但不发出警告的函数。

pd: 一个可能的解决方案是在末尾添加一个非空行并将其删除,但我在徘徊是否有一些实现的功能实际上运行良好,没有使用技巧...

我最近也遇到过这个问题。 我为绕过此警告所做的只是在使用 strftime 之前首先检查日期值是否为非 NaN。

示例:

if df['date'].isnull().values == False:
  df['date'] = df['date'].dt.strftime('%b %d, %Y')

如果您需要检查日期列的任何/所有 nan 值:

语法:

df['your column name'].isnull().values.any()
df['your column name'].isnull().values.all()

这是考虑 NaT 值 (Pandas>=1.0.0) 的更惯用的方法,正如@finavatar 所建议的那样:

import pandas as pd

series = pd.Series([None, None, None], dtype="datetime64[ns]")

series = series.apply(lambda x: x.strftime("%d-%m-%Y") if x is not pd.NaT else x)

print(series)  # No warning message
# Output
0   NaT
1   NaT
2   NaT
dtype: datetime64[ns]

并且有一个非空系列:

import pandas as pd

series = pd.Series(["04/03/2022", None, None], dtype="datetime64[ns]")

series = series.apply(lambda x: x.strftime("%d-%m-%Y") if x is not pd.NaT else x)

print(series)  # No warning message
0    03-04-2022
1           NaT
2           NaT
dtype: object  # == string