Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to_datetime assemblage error due to extra keys

Tags:

python

pandas

My pandas version is 0.23.4.

I tried to run this code:

df['date_time'] = pd.to_datetime(df[['year','month','day','hour_scheduled_departure','minute_scheduled_departure']])  

and the following error appeared:

extra keys have been passed to the datetime assemblage: [hour_scheduled_departure, minute_scheduled_departure]

Any ideas of how to get the job done by pd.to_datetime?

@anky_91

In this image an extract of first 10 rows is presented. First column [int32]: year; Second column[int32]: month; Third column[int32]: day; Fourth column[object]: hour; Fifth column[object]: minute. The length of objects is 2.

like image 933
D. Mac Avatar asked Jan 01 '23 10:01

D. Mac


1 Answers

Another solution:

>>pd.concat([df.A,pd.to_datetime(pd.Series(df[df.columns[1:]].fillna('').values.tolist(),name='Date').map(lambda x: '0'.join(map(str,x))))],axis=1)

    A   Date
0   a   2002-07-01 05:07:00
1   b   2002-08-03 03:08:00
2   c   2002-09-05 06:09:00
3   d   2002-04-07 09:04:00
4   e   2002-02-01 02:02:00
5   f   2002-03-05 04:03:00

For the example you have added as image (i have skipped the last 3 columns due to save time)

>>df.month=df.month.map("{:02}".format)
>>df.day = df.day.map("{:02}".format)
>>pd.concat([df.A,pd.to_datetime(pd.Series(df[df.columns[1:]].fillna('').values.tolist(),name='Date').map(lambda x: ''.join(map(str,x))))],axis=1)

    A   Date
0   a   2015-01-01 00:05:00
1   b   2015-01-01 00:01:00
2   c   2015-01-01 00:02:00
3   d   2015-01-01 00:02:00
4   e   2015-01-01 00:25:00
5   f   2015-01-01 00:25:00
like image 123
anky Avatar answered Jan 16 '23 03:01

anky