将 NaN 转换为 DataFrame 中的数字时出现 TyperError

TyperError when converting NaN's into number in DataFrame

我有一个 DataFrame df,如下所示,我正在尝试将 closing_price 列中有 NaN 的所有情况转换为 100。

   maturity_dt              pay_freq_cd   coupon closing_price FACE_VALUE  
0   2017-06-30 00:00:00.0           2    0.625      99.96875        100   
1   2015-07-15 00:00:00.0           2      1.6         99.47        100   
2   2018-06-15 00:00:00.0           2    1.125      100.3906        100   
3   2015-07-13 00:00:00.0           2      2.1           NaN        100 

我尝试使用下面的代码执行此操作,但在 price_array = np.where(np.isnan(price_array), 100, price_array).

行中出现错误 TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
price_array = df['closing_price'].values
price_array = np.where(np.isnan(price_array), 100, price_array)

请改用 Pandas' fillna() 方法。在你的情况下你可以写:

df['closing_price'].fillna(100)

这会将 'closing_price' 列中的 NaN 值替换为值 100。Pandas 可以正确处理不同的数据类型。 (记得将新列分配回 DataFrame 或使用 inplace=True。)


您看到的错误是 'closing_price' 列具有 object 数据类型的结果。 np.isnan 需要一个浮点值数组。要解决此问题,您可以使用

将列转换为浮动类型
df['closing_price'] = df['closing_price'].astype(float)

...然后照常使用您的方法(尽管我仍然喜欢 fillna())。