如何将一些字符串值分配给对象类型的空白元素
how to assign some string value to the object type blank element
如果我使用下面的代码 select 空白元素,我会出错,如果我使用 row['col'] == np.nan / 'nan' /'NaN' 等
col 是一个对象类型,我想将 val = str('...') 赋值给这些空白元素
if np.isnan(row['col']) == True:
val = str('somewords')
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''
IIUC:
您需要带布尔掩码的 loc 访问器:
row.loc[row['col'].isna(),'col']='somewords'
#^ ^
#checking if the the value is NaN then assigning value
或
使用 numpy 的 where()
方法:
row['col']=np.where(row['col'].isna(),'somewords',row['col'])
#^ ^ ^
#checking if the the value is NaN.
# then assigning value
#If not then get the original value
或
通过fillna()
方法(但在这种情况下当你想有条件地填充NaN时它会失败):
row['col']=row['col'].fillna('somewords')
如果我使用下面的代码 select 空白元素,我会出错,如果我使用 row['col'] == np.nan / 'nan' /'NaN' 等
col 是一个对象类型,我想将 val = str('...') 赋值给这些空白元素
if np.isnan(row['col']) == True:
val = str('somewords')
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''
IIUC:
您需要带布尔掩码的 loc 访问器:
row.loc[row['col'].isna(),'col']='somewords'
#^ ^
#checking if the the value is NaN then assigning value
或
使用 numpy 的 where()
方法:
row['col']=np.where(row['col'].isna(),'somewords',row['col'])
#^ ^ ^
#checking if the the value is NaN.
# then assigning value
#If not then get the original value
或
通过fillna()
方法(但在这种情况下当你想有条件地填充NaN时它会失败):
row['col']=row['col'].fillna('somewords')