为了账号安全,请及时绑定邮箱和手机立即绑定

通过根据另一列中的条件更改一列中的值返回错误

通过根据另一列中的条件更改一列中的值返回错误

Smart猫小萌 2022-07-26 21:03:22
有一个dfrequest_type start_date  end_datemain         2020-02-12  2020-02-12main         2020-02-12  2020-02-12main         2020-02-12  2020-02-12meta         2020-02-10  2020-02-10meta         2020-02-10  2020-02-10如果 request_type 是 main,我需要将“00:00:00”添加到 start_date 和 end_date 列的值我尝试的是df['start_date'] = np.where(df.request_type == 'main', df.start_date + ' 00:00:00', df.start_date)我收到了这个错误TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str'那好吧df['start_date'] = np.where(df.request_type == 'main', df.start_date.dt.strftime('%Y-%m-%d') + ' 00:00:00', df.start_date)然后我收到了这个错误AttributeError: Can only use .dt accessor with datetimelike values然后我检查了 start_date 列的类型,它是一个对象我不知道哪里有错误以及如何解决它感谢任何帮助我的理想结果是request_type start_date           end_datemain         2020-02-12 00:00:00  2020-02-12 00:00:00main         2020-02-12 00:00:00  2020-02-12 00:00:00main         2020-02-12 00:00:00  2020-02-12 00:00:00meta         2020-02-10           2020-02-10meta         2020-02-10           2020-02-10
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

这是可能的,但是得到混合值 - 在一列中带有和 python 日期对象的字符串00:00:00,所以接下来的处理应该是有问题的:


df['start_date'] = np.where(df.request_type == 'main', 

                            pd.to_datetime(df.start_date).dt.strftime('%Y-%m-%d 00:00:00'),

                            df.start_date)

或者:


df['start_date'] = np.where(df.request_type == 'main', 

                            df.start_date.astype(str) +' 00:00:00',

                            df.start_date)

print (df)

  request_type           start_date    end_date

0         main  2020-02-12 00:00:00  2020-02-12

1         main  2020-02-12 00:00:00  2020-02-12

2         main  2020-02-12 00:00:00  2020-02-12

3         meta           2020-02-10  2020-02-10

4         meta           2020-02-10  2020-02-10


print (df['start_date'].apply(type))

0              <class 'str'>

1              <class 'str'>

2              <class 'str'>

3    <class 'datetime.date'>

4    <class 'datetime.date'>

Name: start_date, dtype: object


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号