簡體   English   中英

如何從混合格式的列中提取年份

[英]How to extract year from a column with mixed formats

我的數據集中有一列看起來有許多不同格式的日期。 有時它只有年月,有時只有年:

日期
1980年1月1日
74 年 10 月
10月17日
1980.0
-200
-50
8個

我只想從此列中提取年份。 對於格式為“mmm-yy”的日期,我想假設它們在 1921 年到 2020 年之間。所以我的上列應該如下所示:

1980
1974年
2017年
1980
-200
-50
8個

我如何在 Python 中執行此操作? 任何幫助,將不勝感激。

#here is the code for the first dataframe
data = {'date': ['1 January 1980','Oct-74', 'Oct-17', '1980.0', '-200.0', '-50']}  
df= pd.DataFrame(data)
df

嘗試這個:

data = {'date': ['1 January 1980','Oct-74', 'Oct-17', '1980.0', '-200.0', '-50', '8']}  
df= pd.DataFrame(data)
temp = df['date'].str.replace('[a-zA-Z]{3}-', '+').str.extract('([-+\.\d]{1,}$)')
m1 = temp[0].str.contains('\+')
temp[0] = temp[0].astype(float)
temp[0] = temp[0].where(~((m1)&(temp[0]>=21)), 1900+temp[0])
temp[0] = temp[0].where(~((m1)&(temp[0]<21)), 2000+temp[0])

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM