由于额外的键,to_datetime组装错误

D. *_*Mac 4 python pandas

我的熊猫版本是0.23.4。

我试图运行以下代码:

df['date_time'] = pd.to_datetime(df[['year','month','day','hour_scheduled_departure','minute_scheduled_departure']])  
Run Code Online (Sandbox Code Playgroud)

并且出现以下错误:

额外的键已传递给日期时间组合:[hour_scheduled_departure,minute_scheduled_departure]

关于如何通过pd.to_datetime完成工作的任何想法?

@ anky_91

在此图像中,显示了前10行的摘录。第一列[int32]:年份;第二列[int32]:月;第三栏[int32]:日期;第四栏[对象]:小时;第五列[对象]:分钟。对象的长度是2。

ank*_*_91 5

另一个解决方案:

>>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
Run Code Online (Sandbox Code Playgroud)

对于您添加为图像的示例(由于节省时间,我跳过了最后3列)

>>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
Run Code Online (Sandbox Code Playgroud)