[英]object is unsliceable error when using to_datetime pandas method
I am learning to use pandas library of python.我正在学习使用 python 的 pandas 库。 I was trying to use to_datetime method and I have this error 'ValueError: cannot assemble the datetimes: 'int' object is unsliceable'.
我试图使用 to_datetime 方法,但出现此错误“ValueError: cannot assemble the datetimes: 'int' object is unsliceable”。
Here my code:这是我的代码:
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()
when I run that the dates df printed seems all right:当我运行 df 打印的日期似乎没问题时:
year month day
0 1969 1 1
1 1969 1 2
2 1969 1 3
3 1969 1 4
4 1969 1 5
Then I run:然后我运行:
pd.to_datetime(dates)
and I got the said error.我得到了上述错误。 What can it be?
会是什么?
Thanks for insights.感谢您的见解。
Just pass errors
parameter in pd.to_datetime()
method and set that equal to 'coerce'
只需在
pd.to_datetime()
方法中传递errors
参数并将其设置为'coerce'
dates=pd.to_datetime(dates,errors='coerce')
Note:- If the above method is creating any problem then use the method below:-注意:-如果上述方法产生任何问题,请使用以下方法:-
use join()
method and for loop
:-使用
join()
方法和for loop
:-
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'])])]))
Then:-然后:-
dates['date']=datetime
Finally use to_datetime()
method:-最后使用
to_datetime()
方法:-
dates['date']=pd.to_datetime(dates['date'],errors='coerce')
dates=dates.drop(columns=['year','month','day'])
Output of dates
:- Output
dates
:-
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
As pointed out by @serge some days have wrong values making the conversion fails.正如@serge 所指出的,有些日子有错误的值导致转换失败。 Once data are filtered it's all fine.
一旦数据被过滤,一切都很好。
Best最好的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.