gpt4 book ai didi

python - 在 pandas.DataFrame 中更改年份

转载 作者:行者123 更新时间:2023-12-04 03:25:35 25 4
gpt4 key购买 nike

我有大量时间序列数据,我想将某个范围内的所有年份更改为 1900 年(例如)。我的 MWE 是

import pandas as pd
from datetime import date

df = pd.DataFrame({
'name': ['alice','bob','charlie'],
'date_of_birth': ['10/25/2005','10/29/2002','01/01/2001']})

# convert to type datetime
df['date_of_birth'] = pd.to_datetime(df['date_of_birth'])
print(df)

df['date_of_birth'] = df['date_of_birth'].mask(df['date_of_birth'].dt.year > 2000, \
df['date_of_birth'] - pd.to_timedelta(100, unit='y') + \
pd.to_timedelta(12, unit='h'))
print(df)

此方法更改年、月和日。有没有办法只更改年份而其他一切保持原样?

最佳答案

我们可以使用date.replace :

s = df["date_of_birth"].apply(lambda x: x.replace(year=1900))
df["date_of_birth"] = np.where(df["date_of_birth"].dt.year > 2000, s, df["date_of_birth"])
      name date_of_birth
0 alice 1900-10-25
1 bob 1900-10-29
2 charlie 1900-01-01

关于python - 在 pandas.DataFrame 中更改年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67678151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com