"Out of bounds nanosecond timestamp"?你如何避免这个错误?

"Out of bounds nanosecond timestamp"? How do you avoid this error?

我有一个数组,被识别为 'numpy.ndarray object' 当 运行 执行以下代码时打印以下输出:

with sRW.SavReaderNp('C:/Users/Sam/Downloads/Data.sav') as reader:
record = reader.all()
print(record)

输出:

[(b'61D8894E-7FB0-3DE6-E053-6C04A8C01207', b'Sam', 250000., '2019-08-05T00:00:00.000000')
 (b'61D8894E-7FB0-3DE6-E053-6C04A8C01207', b'James',  250000., '2019-08-05T00:00:00.000000')
 (b'61D8894E-7FB0-3DE6-E053-6C04A8C01207', b'Mark', 250000., '0001-01-01T00:00:00.000000')

我真的想使用 pd.DataFrame 格式处理 pandas DataFrame 中的空日期变量,但是当我 运行 下面的代码出现错误时(如下代码所示) :

SPSS_df = pd.DataFrame(record)

Error: "Out of bounds nanosecond timestamp: 1-01-01 00:00:00"

我通读了 SavReader 模块文档的源代码,它说如果找不到日期时间值,则会分配以下日期:

datetime.datetime(datetime.MINYEAR, 1, 1, 0, 0, 0)

我想知道如何在不遇到此错误的情况下处理此日期,也许 changing/maniuplating 上面的代码?

您可以做的是将所有记录读取为字符串(对象),然后将列转换为所需的类型(浮点数和日期时间)

import numpy as np
import pandas as pd

record = [
    (
        b'61D8894E-7FB0-3DE6-E053-6C04A8C01207',
        b'Sam',
        250000.0,
        '2019-08-05T00:00:00.000000',
    ),
    (
        b'61D8894E-7FB0-3DE6-E053-6C04A8C01207',
        b'James',
        250000.0,
        '2019-08-05T00:00:00.000000',
    ),
    (
        b'61D8894E-7FB0-3DE6-E053-6C04A8C01207',
        b'Mark',
        250000.0,
        '0001-01-01T00:00:00.000000',
    ),
]

SPSS_df = pd.DataFrame(record, dtype=object).rename(
    {2: 'some_float', 3: 'dates'}, axis='columns'
).assign(
    some_float=lambda x: x['some_float'].astype(np.float),
    dates=lambda x: pd.to_datetime(x['dates'], errors='coerce'),
)

这给出:

0  b'61D8894E-7FB0-3DE6-E053-6C04A8C01207'    b'Sam'    250000.0 2019-08-05
1  b'61D8894E-7FB0-3DE6-E053-6C04A8C01207'  b'James'    250000.0 2019-08-05
2  b'61D8894E-7FB0-3DE6-E053-6C04A8C01207'   b'Mark'    250000.0        NaT

和类型:

SPSS_df.dtypes
0                     object
1                     object
some_float           float64
dates         datetime64[ns]