我有一个带有日期列的csv,日期列为MM / DD / YY,但我想将年份从00,02,03更改为1900、1902和1903,以便将它们改为MM / DD / YYYY
这对我有用:
df2['Date'] = df2['Date'].str.replace(r'00', '1900')
但是我每年必须这样做,直到68岁(又是重复68次)。我不确定如何在该范围内每年创建一个循环来执行上述代码。我尝试过:
ogyear=00
newyear=1900
while ogyear <= 68:
df2['date']=df2['Date'].str.replace(r'ogyear','newyear')
ogyear += 1
newyear += 1
但是这将返回一个空的数据集。还有另一种方法吗?
我不能使用datetime,因为它假定02表示2002而不是1902,并且当我尝试将其作为日期进行编辑时,我收到了一条来自python的错误消息,提示日期是不可变的,因此必须在原始数据集。因此,我需要将日期保留为字符串。如果有帮助,我还会在此处附加csv。
答案 0 :(得分:0)
我会这样:
# create a data frame
d = pd.DataFrame({'date': ['20/01/00','20/01/20','20/01/50']})
# create year column
d['year'] = d['date'].str.split('/').str[2].astype(int) + 1900
# add new year into old date by replacing old year
d['new_data'] = d['date'].str.replace('[0-9]*.$','') + d['year'].astype(str)
date year new_data
0 20/01/00 1900 20/01/1900
1 20/01/20 1920 20/01/1920
2 20/01/50 1950 20/01/1950
答案 1 :(得分:0)
我将通过以下方式进行操作:
from datetime import datetime
# create a data frame with dates in format month/day/shortened year
d = pd.DataFrame({'dates': ['2/01/10','5/01/20','6/01/30']})
#loop through the dates in the dates column and add them
#to list in desired form using datetime library,
#then substitute the dataframe dates column with the new ordered list
new_dates = []
for date in list(d['dates']):
dat = datetime.date(datetime.strptime(date, '%m/%d/%y'))
dat = dat.strftime("%m/%d/%Y")
new_dates.append(dat)
new_dates
d['dates'] = pd.Series(new_dates)
d