Python 从数据框中删除年份

Python 从数据框中删除年份,python,pandas,Python,Pandas,我有一个数据帧df,具有以下列: df['DateofBirth'] = 1 5/12/2005 2 20/12/2009 3 20/11/1991 4 2/12/1997 该列的元素为日期/月/年。我想从本专栏中创建一个只包含年份的新数据框架。我尝试过这个解决方案,但它不起作用如果列是字符串类型且其格式是常量,我们可以将str访问器与split一起使用 >>> df DateofBirth 0 5/12/2005 1

我有一个数据帧df,具有以下列:

df['DateofBirth'] =
    1   5/12/2005
    2   20/12/2009
    3   20/11/1991
    4   2/12/1997

该列的元素为日期/月/年。我想从本专栏中创建一个只包含年份的新数据框架。我尝试过这个解决方案,但它不起作用

如果列是字符串类型且其格式是常量,我们可以将
str
访问器与
split
一起使用

>>> df
  DateofBirth
0   5/12/2005
1  20/12/2009
2  20/11/1991
3   2/12/1997
>>> df["DateofBirth"].str.split("/").str[2]
0    2005
1    2009
2    1991
3    1997
Name: DateofBirth, dtype: object

如果列为字符串类型且其格式为常量,则可以将
str
访问器与
split
一起使用

>>> df
  DateofBirth
0   5/12/2005
1  20/12/2009
2  20/11/1991
3   2/12/1997
>>> df["DateofBirth"].str.split("/").str[2]
0    2005
1    2009
2    1991
3    1997
Name: DateofBirth, dtype: object

你为什么不找个合适的约会时间呢
dt=pd.to_datetime(df['DateOfBirth'],dayfirst=True)
然后您可以调用
dt.year
为什么不将其转换为适当的日期时间
dt=pd.to_datetime(df['DateOfBirth'],dayfirst=True)
然后您可以调用
dt.year