如何将年份列转换为默认日期

时间:2019-09-11 17:26:03

标签: pandas

给出一列年份:

Years
2016
2015
2015
2017
2016

如何将这些年份转换为默认为1月1日的日期?

Years
2016-01-01
2015-01-01
2015-01-01
2017-01-01
2016-01-01

我对编程很陌生,尝试解决方案使我的大脑受伤。我想我需要编写某种函数来转换年份。

def convert_years(year):
    return converted_year

我知道这是一项辛苦的工作,但是我不知道该怎么办。我已经在Stack Overflow上搜索了两个小时,没有任何进展。谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用年份中的datetime.date创建日期。

import datetime
df['Years'] = df['Years'].apply(lambda x: datetime.date(int(x), 1, 1))

答案 1 :(得分:0)

您也可以这样:

df['Years']= pd.to_datetime(df['Years'], format='%Y')

它使用本机熊猫(numpy)数据类型datetime64填充列。

编辑:如果您的列中包含无法解释为有效年份的其他值,我建议添加另一列,其转换日期保持原值不变。您可以按照以下步骤进行操作:

# create a new column and initialize it as datetime
df['date']= pd.Series(dtype='datetime64[ns]')

# setup an indexer that identifies the valid year values
# here I assume column Years contains strings and 
# as an example only want to consider strings to be valid years
# if the string consists of exactly 4 digits and is between
# 1980 and 2050
indexer= df['Years'].str.match('^[0-9]{4}$') & (df['Years']>'1980') & (df['Years']<'2050')

# now set the new date column for all rows with a valid year in
# Years to that date (all others remain as NaT
df.loc[indexer, 'date']= pd.to_datetime(df.loc[indexer, 'Years'], format='%Y')