簡體   English   中英

如何從具有不同日期格式字符串的列中提取年份

[英]How to extract the year from a column with different date formatted strings

我有一個 dataframe 列,其中包含不同類型的字符串,如下所示:

    year
0   1990
1   1998.0
2   2006-02-12

我只想從它們中提取年份並將它們轉換為intfloat

    year
0   1990
1   1998
2   2006

假設這些是唯一的模式,您可以使用str.extract

import pandas as pd

df = pd.DataFrame(data=['1990','1998.0','2006-02-12'], columns=['year'])

result = df.year.str.extract('^(\d{4})')
print(result)

Output

      0
0  1990
1  1998
2  2006

模式^(\d{4})轉換為開始字符串的前 4 位數字,因此您基本上是在提取列中每個字符串的前 4 位數字。

暫無
暫無

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

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