首页 > 解决方案 > 通过根据另一列中的条件更改一列中的值返回错误

问题描述

有一个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

标签: pythonpandasnumpy

解决方案


这是可能的,但是得到混合值 - 在一列中带有和 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

推荐阅读