我正在尝试使用 loc 方法更新 pandas 数据框中选定的 datetime64 值来选择满足条件的行。但是,它不会分配新的日期时间值,而是生成 NaT。
这是我的代码的简化,显示了问题:
import pandas as pd
import numpy as np
datetime = (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 days
df['new_date'] = df['date_time'] - pd.Timedelta(180, unit='d')
# replace datetime with new date where select is true
df.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.
关于如何做到这一点或为什么这没有按预期工作的任何想法?
慕森卡
相关分类