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

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

如何更新 pandas 數據框中選定的 datetime64 值?

如何更新 pandas 數據框中選定的 datetime64 值?

月關寶盒 2023-08-08 15:11:56
我正在嘗試使用 loc 方法更新 pandas 數據框中選定的 datetime64 值來選擇滿足條件的行。但是,它不會分配新的日期時間值,而是生成 NaT。這是我的代碼的簡化,顯示了問題:import pandas as pdimport numpy as npdatetime = (np.datetime64('1899-12-30'), np.datetime64('1989-12-30'), np.datetime64('2199-12-30'))select = (0, 1, 0)df = pd.DataFrame(list(zip(datetime, select)),? ? ? ? ? ? ? ? ? columns=['date_time', 'select'])# create a new column by subtracting 180 daysdf['new_date'] = df['date_time'] - pd.Timedelta(180, unit='d')# replace datetime with new date where select is truedf.loc[(df['select'] == 1), ['date_time']] = df.loc[(df['select'] == 1), ['new_date']]print(df)# the second element of the date_time column is "NaT", but this is not the desired outcome.# the desired behaviour is for it to be the same as the second element in the new_date column.關于如何做到這一點或為什么這沒有按預期工作的任何想法?
查看完整描述

1 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

您應該[]在列名稱周圍放置:

df.loc[(df['select'] == 1), 'date_time'] = df.loc[(df['select'] == 1), 'new_date']

您還可以刪除第二個布爾索引:

df.loc[(df['select'] == 1), 'date_time'] = df['new_date']

另外,np.where

df['date_time'] = np.where(df['select']==1, df['new_date'], df['date_time'])

說明:對數據幀df.loc[s, ['col_name']]進行切片,對系列進行切片。當你這樣做時:df.loc[s, 'col_name']

dataframe_slice = another_dataframe_slice

Pandas 將嘗試對齊兩個數據幀的索引/列。在這種情況下,兩個切片沒有公共列,因此更新后的數據幀的NaN值為select==1。


查看完整回答
反對 回復 2023-08-08
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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