【问题标题】:Change year in pandas.DataFrame在 pandas.DataFrame 中更改年份
【发布时间】:2021-08-13 02:49:38
【问题描述】:

我有大量时间序列数据,我想将某个范围内的所有年份更改为 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)

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

【问题讨论】:

  • 为什么要加pd.to_timedelta(12, unit='h')?你需要那个还是测试?
  • 你是对的,那一点是没有必要的

标签: python pandas dataframe datetime


【解决方案1】:

我们可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2013-03-01
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多