ValueError:时间数据“1980-02-10”与格式“%y%m%d”不匹配(匹配)pandas

我有一张包含 DateOfBirth 列的表,如下所示:

     Gender  FullName           DateOfBirth
0    Male      Stan Smith       1980-02-10
1    Male      Nikola Griffin   1999-12-20
2    Female    Ruby Moore       1986-03-03

我想根据这个答案/sf/answers/1875270141/找出每个全名的年龄,我正在这样做

import datetime as DT

import io

import numpy as np

import pandas as pd
name = {'Gender': ['Male','Male','Female'],
        'FullName': ['Stan Smith','Nikola Griffin','Ruby Moore'],
        'DateOfBirth' : ['1980-02-10', '1999-12-20', '1986-03-03']
        }

df = pd.DataFrame(name, columns = ['Gender', 'FullName', 'DateOfBirth'])

now = pd.Timestamp('now')

df['DateOfBirth'] = pd.to_datetime(df['DateOfBirth'], format='%y%m%d'

但是当我做最后一个代码时,它说 ValueError: time data '1980-02-10' does not match format '%y%m%d' (match)

回答

您正在设置%y%m%d相当于 YearMonthDay的日期格式,但是数据用连字符分隔年、月和日。因此,您需要在代码的最后一行反映这一点

同样来自文档的 %y是两位数的年份(80、99、86)。您需要%Y改为,因为这是一个四位数年份(1980、1999、1986)。

因此你的最后一行应该是

df['DateOfBirth'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d')


以上是ValueError:时间数据“1980-02-10”与格式“%y%m%d”不匹配(匹配)pandas的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>