Skip to main content
 首页 » 编程设计

python之numpy.where : TypeError: invalid type promotion

2025年05月04日23zhwl

我知道还有其他问题具有相同的错误名称,但没有一个与 np.where 语句匹配,而且我也找不到问题的答案

所以我制作了一个名为 data 的 pandas DataFrame 并从中创建了一个名为 dates 的 Series,它是:

dates= pd.to_datetime(pd.to_timedelta(data.a_date, unit= 'D') + pd.datetime(1960,1,1),  
                      errors= 'coerse') 

我需要清除一些日期,因为它们与 data 中的指示符不匹配,所以我尝试使用 numpy.where< 来调整它,同时保持索引正确,
然而我得到了这个错误:

--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-18-2b83ed2b2468> in <module>() 
----> 1 np.where(((dates.notnull()) & (data.a_IND == 0)), np.nan, dates) 
 
TypeError: invalid type promotion 

请您参考如下方法:

如果要保留日期类型,请将 np.nan 替换为 np.datetime64('NaT'):

np.where(((dates.notnull()) & (data.a_IND == 0)), np.datetime64('NaT'), dates)