Convert row index "% m /% d /% Y" to pandas datetime index

MY index is a datetime string with the format '%m/%d/%Y' ('09/26/2007')

When I try to convert an index to a datetime index using pd.to_datetimefunction pd.to_datetime(df.index), I got an errorOutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00

It seems that pandas cannot determine the correct string format, how can I convert an index to a datetime index?

thank

+4
source share
1 answer

The appearance of the error message, it looks like you might have a row '1/1/0001'in your index. For instance,

df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001'])
pd.to_datetime(df.index)

causes

OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00

- , DatetimeIndex NumPy datetime64[ns], 0001-01-01. datetime64[ns] dtype [1678 AD, 2262 AD].

pandas github, .

PeriodIndex DatetimeIndex:

df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001'])
df.index = pd.PeriodIndex(df.index, freq='D')

            0
2007-09-26  1
1-01-01     2
+4

Source: https://habr.com/ru/post/1652238/


All Articles