python - 通过根据另一列中的条件更改一列中的值返回错误
问题描述
有一个df
request_type start_date end_date
main 2020-02-12 2020-02-12
main 2020-02-12 2020-02-12
main 2020-02-12 2020-02-12
meta 2020-02-10 2020-02-10
meta 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_date
main 2020-02-12 00:00:00 2020-02-12 00:00:00
main 2020-02-12 00:00:00 2020-02-12 00:00:00
main 2020-02-12 00:00:00 2020-02-12 00:00:00
meta 2020-02-10 2020-02-10
meta 2020-02-10 2020-02-10
解决方案
这是可能的,但是得到混合值 - 在一列中带有和 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
推荐阅读
- java - 通过 Jena 权限示例教程获取 NoClassDefFoundError
- c# - 从字符串中转义定义的特殊字符
- java - Java - 如何将方形数组(二维)向右旋转 90 度?
- docker - Go 1.11 Docker build 中自己的包的未知导入路径
- r - 自定义R中的排序功能
- raspberry-pi - 播放视频时,Raspberry Pi 3 上的 Gstreamer 噼啪声
- oracle - 为什么我的 Oracle ORDS 插件不起作用?
- excel - 如果 X 和 Y 为空,则邮件合并跳过
- reactjs - antd 不导入所有图标
- c# - 验证输入 DataGridView 的日期