亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過根據另一列中的條件更改一列中的值返回錯誤

通過根據另一列中的條件更改一列中的值返回錯誤

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 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號