如何更改numpy datetime64中的年份值?

Mar*_*ark 3 python numpy pandas

我有一个 Pandas DataFrame,里面有dtype=numpy.datetime64 我想更改的数据

'2011-11-14T00:00:00.000000000'
Run Code Online (Sandbox Code Playgroud)

到:

'2010-11-14T00:00:00.000000000'
Run Code Online (Sandbox Code Playgroud)

或其他年份。Timedelta 未知,只能分配年份编号。这在 int 中显示年份

Dates_profit.iloc[50][stock].astype('datetime64[Y]').astype(int)+1970
Run Code Online (Sandbox Code Playgroud)

但不能赋值。有人知道如何分配年份numpy.datetime64吗?

Max*_*axU 6

由于您使用的是 DataFrame,请考虑使用pandas.Timestamp.replace:

In [1]: import pandas as pd

In [2]: dates = pd.DatetimeIndex([f'200{i}-0{i+1}-0{i+1}' for i in range(5)])

In [3]: df = pd.DataFrame({'Date': dates})

In [4]: df
Out[4]:
        Date
0 2000-01-01
1 2001-02-02
2 2002-03-03
3 2003-04-04
4 2004-05-05

In [5]: df.loc[:, 'Date'] = df['Date'].apply(lambda x: x.replace(year=1999))

In [6]: df
Out[6]:
        Date
0 1999-01-01
1 1999-02-02
2 1999-03-03
3 1999-04-04
4 1999-05-05
Run Code Online (Sandbox Code Playgroud)