Python 使用to_datetime方法时,对象是不可许可的错误
我正在学习使用python的熊猫库。我试图使用to_datetime方法,但出现以下错误“ValueError:无法组装datetimes:“int”对象不可许可” 这是我的代码:Python 使用to_datetime方法时,对象是不可许可的错误,python,pandas,Python,Pandas,我正在学习使用python的熊猫库。我试图使用to_datetime方法,但出现以下错误“ValueError:无法组装datetimes:“int”对象不可许可” 这是我的代码: import numpy as np import pandas as pd from urllib import request request.urlretrieve ("https://raw.githubusercontent.com/jakevdp/data-CDCbirths/master/bi
import numpy as np
import pandas as pd
from urllib import request
request.urlretrieve ("https://raw.githubusercontent.com/jakevdp/data-CDCbirths/master/births.csv","births.csv")
births= pd.read_csv('births.csv')
births=births.groupby(['year','month','day'],as_index=False).agg('sum')
dates=births.drop(['births'],axis=1)
dates=dates.astype('int')
dates.head()
当我运行时,打印的日期似乎没有问题:
year month day
0 1969 1 1
1 1969 1 2
2 1969 1 3
3 1969 1 4
4 1969 1 5
然后我跑:
pd.to_datetime(dates)
我得到了上面说的错误。
可能是什么
感谢您的见解。只需将
pd.to_datetime()
方法中的errors
参数传递给方法,并将其设置为等于的“强制”
dates=pd.to_datetime(dates,errors='coerce')
注意:-如果上述方法产生任何问题,请使用以下方法:-
对循环使用join()
方法和:-
datetime=[]
for x in range(0,len(dates)):
datetime.append(' '.join(['-'.join([str(dates.loc[x,'year']),str(dates.loc[x,'month']),str(dates.loc[x,'day'])])]))
然后:-
dates['date']=datetime
最后使用到\u datetime()
方法:-
dates['date']=pd.to_datetime(dates['date'],errors='coerce')
dates=dates.drop(columns=['year','month','day'])
日期的输出
:-
date
0 1969-01-01
1 1969-01-02
2 1969-01-03
3 1969-01-04
4 1969-01-05
... ...
7562 1988-12-27
7563 1988-12-28
7564 1988-12-29
7565 1988-12-30
7566 1988-12-31
正如@serge所指出的,有些天的值错误,导致转换失败。一旦数据被过滤,一切都很好
最佳年
、月
和日
以及直接由pd.to\u datetime
处理的特殊名称。如果days列包含错误的数据,问题是…哇…我不知道这件事…谢谢你告诉/分享这些信息:)我也直到今天才知道。。。但是在文档中有一个很好的例子,用于pd.to\u datetime
。