简体   繁体   English

使用Python更改“日期中的年份”列,而不更改月份和日期

[英]Change the Year in Date column without changing the month and day using Python

I have to fix the year in column 'Date Posted'. 我必须在“发布日期”列中确定年份。 Some of the dates were mistyped as '2019' instead of '2017' (See Current Dataframe below). 一些日期被误输入为“ 2019”而不是“ 2017”(请参见下面的当前数据框)。 Is there a way to fix only the year without changing the month and day? 有没有一种方法可以只修复年份而不更改月份和日期? This dataframe is a subset of a huge dataframe and I need to automate the fixing of date error. 此数据框是一个巨大数据框的子集,我需要自动修复日期错误。 Please help. 请帮忙。

Current Dataframe: 当前数据框:

Name                  Date Posted
A                        10-28-2017
A                        10-28-2017
A                        10-26-2017
A                        10-24-2017 
B                        10-02-2019
B                        10-08-2019
B                        10-04-2017
B                        10-05-2019
C                        9-15-2017
C                        9-02-2017 
C                        9-07-2017
C                        9-16-2017

Expected Output: 预期产量:

Name                  Date Posted
A                        10-28-2017
A                        10-28-2017
A                        10-26-2017
A                        10-24-2017 
B                        10-02-2017
B                        10-08-2017
B                        10-04-2017
B                        10-05-2017
C                        9-15-2017
C                        9-02-2017 
C                        9-07-2017
C                        9-16-2017

If your Date Posted columns is in datetime format, can use the replace function. 如果您的“ Date Posted datetime Date Posted格式,则可以使用replace功能。 Below should work: 下面应该工作:

df["Date Posted"].map(lambda x: x.replace(year=2017))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM