使用np.where处理pandas datetime列返回object dtype是否符合预期?
问题原因
当你用np.where处理pandas datetime列时,因为传入的替换值是单个pandas Timestamp标量,而原列是datetime64[ns]类型的Series,np.where会将两者混合后返回object类型的numpy数组——numpy无法将Timestamp标量和datetime64数组元素统一为datetime64类型,只能退而求其次用object类型容纳不同对象。
解决方案
以下是几种高效的解决方法,按推荐优先级排序:
1. 用pandas原生fillna(最简洁)
这是处理datetime列缺失值的最优方式,原生支持保持datetime类型:
# 直接赋值写法 example_df["same_time"] = example_df["time"].fillna(pd.to_datetime('1900-01-01 00:00:00')) # 链式处理写法 example_df = example_df.assign( same_time=lambda df_: df_["time"].fillna(pd.to_datetime('1900-01-01 00:00:00')) )
2. 让np.where的替换值与原列类型匹配
确保替换值和原列的元素类型一致,让np.where能返回datetime64类型的数组:
# 方案2.1:将替换值转为numpy datetime64类型 replace_val = np.datetime64('1900-01-01 00:00:00') example_df["same_time"] = np.where(example_df["time"].isna(), replace_val, example_df["time"]) # 方案2.2:将替换值转为同长度的datetime Series replace_series = pd.Series( [pd.to_datetime('1900-01-01 00:00:00')]*len(example_df), dtype='datetime64[ns]' ) example_df["same_time"] = np.where(example_df["time"].isna(), replace_series, example_df["time"])
3. 生成后强制转换类型
如果坚持用np.where,可在生成后强制转回datetime类型:
example_df["same_time"] = np.where( example_df["time"].isna(), pd.to_datetime('1900-01-01 00:00:00'), example_df["time"] ).astype('datetime64[ns]')
内容的提问来源于stack exchange,提问作者Balthazar
相关产品推荐
相关产品推荐

