简体   繁体   English

如何用 pandas 中的字符串值替换 NaN

[英]How to replace NaN with a string value in pandas

I am working on the Kaggle Housing Prices project.我正在从事 Kaggle 房价项目。 I have tried for several hours to replace the NaN values in a string column 'BsmtQual'.我已经尝试了几个小时来替换字符串列“BsmtQual”中的 NaN 值。 For all houses with a SalePrice of less than 120000 that have a NaN value in the BsmtQual column, I want to replace it with 'Fa'.对于在 BsmtQual 列中具有 NaN 值的 SalePrice 小于 120000 的所有房屋,我想将其替换为“Fa”。

df is my dataframe. df 是我的 dataframe。

Fa_rng = df['SalePrice'] < 120000

I have attempted all the below and they did not change anything.我已经尝试了以下所有方法,但它们没有改变任何东西。

df.loc[Fa_rng,'BsmtQual'].fillna('Fa',inplace=True)
df.loc[Fa_rng,'BsmtQual'].replace('NaN','Fa',inplace=True)
df.loc[Fa_rng,'BsmtQual'].str.replace('NaN','Fa')

This one gets a warning saying "A value is trying to be set on a copy of a slice from a DataFrame" and does nothing.这会收到一条警告,说“试图在数据帧的切片副本上设置一个值”并且什么都不做。

df.loc[(df['BsmtQual'].isna()) & (df['SalePrice'] < 120000)].fillna('Fa',inplace=True)

How do I replace a NaN value in pandas for those houses to a 'Fa' string?如何将这些房屋的 pandas 中的 NaN 值替换为“Fa”字符串?

Don't use inplace :不要inplace使用:

df.loc[Fa_rng & df['BsmtQual'].isna(),'BsmtQual'] = 'Fa'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM