【问题标题】:pandas to_datetime not working with numpy where熊猫 to_datetime 不与 numpy 一起工作
【发布时间】:2022-12-09 23:25:45
【问题描述】:

我有一个字符串/对象类型的日期列:

     Day - 2022  Day - 2021  ...
0    01/01/2022  01/01/2021  ...
1    02/01/2022  02/01/2021  ...
2    03/01/2022  03/01/2021  ...
3    04/01/2022  04/01/2021  ...
4    05/01/2022  05/01/2021  ...
..          ...         ...  ...
725  27/12/2023         NaN  ...
726  28/12/2023         NaN  ...
727  29/12/2023         NaN  ...
728  30/12/2023         NaN  ...
729  31/12/2023         NaN  ...

到目前为止,我可以像这样毫无问题地投射:

pd.to_datetime(df["Day - 2022"])
0     2022-01-01
1     2022-02-01
2     2022-03-01
3     2022-04-01
4     2022-05-01
         ...    
725   2023-12-27
726   2023-12-28
727   2023-12-29
728   2023-12-30
729   2023-12-31
Name: Day - 2022, Length: 730, dtype: datetime64[ns]

但是,当我使用 np.where 来检测字符串列是否实际上是字符串格式的日期时,它会返回大整数:

col = "Day - 2022"
pattern = "^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}"
df[col] = np.where(
     df[col].str.match(pattern),
     pd.to_datetime(df[col]),
     df[col],
)
              Day - 2022  Day - 2021  ... 
0    1640995200000000000  01/01/2021  ... 
1    1643673600000000000  02/01/2021  ... 
2    1646092800000000000  03/01/2021  ... 
3    1648771200000000000  04/01/2021  ... 
4    1651363200000000000  05/01/2021  ... 
..                   ...         ...  ... 
725  1703635200000000000         NaN  ... 
726  1703721600000000000         NaN  ... 
727  1703808000000000000         NaN  ... 
728  1703894400000000000         NaN  ... 
729  1703980800000000000         NaN  ... 

对为什么会这样感到困惑?关于如何防止这种情况发生的任何想法?

【问题讨论】:

  • 似乎是纳秒级的时间戳,尝试使用 pd.to_datetime() 参数(单位、原点...)
  • 不知道,但它似乎正在将字符串转换为 UNIX 时间格式,所以只需将其更改为 pd.to_datetime(df[col],unit='ns') 或使用 datetime.datetime.fromtimestamp(1640995200000000000 * 10e-10)
  • 原因是df[col] 是对象类型,默认情况下,在 np.where 中使用日期时间类型(来自pd.to_datetime(df[col]))或对象类型(来自df[col])将导致对象类型数组。我知道在你的例子中,df[col]np.where 中是不可能的,但结果的对象转换可能是之前完成的。试试你自己,如果你投射到对象pd.to_datetime(df["Day - 2022"]).to_numpy().astype('object'),结果是一样的

标签: python pandas


【解决方案1】:

这是对我有用的:

col = "Day - 2022"
pattern = "^(0?[1-9]|[12][0-9]|3[01])[/-](0?[1-9]|1[012])[/-]d{2,4}"
df[col] = np.where(
     df[col].str.match(pattern),
     np.asarray(
        df[col].astype(np.datetime64),
        dtype="datetime64[s]",
     ),
     df[col],
)

所以 np.where 将日期字符串转换为 unix 时间戳的 numpy 数组,然后使用 here 的答案将数组转换为日期时间类型。

【讨论】:

    猜你喜欢
    • 2022-12-16
    • 1970-01-01
    • 2018-06-05
    • 2020-11-17
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多