python - 如何替换 pandas 上过滤的多列中的 nan 值?

标签 python pandas dataframe replace nan

我想单独清理数据框中的 NaN 值。我使用了一些过滤器来查找 NaN 值。但同一过滤器检测到另一列包含 NaN 值。这种情况让我很困惑。我尝试了很多方法,但这些 NaN 值没有改变。

先看我的dataframe;

Raw DataFrame

When the applied filters

pop[(pop['Log GDP per capita'].isna())][(pop['Country name'])=='Somalia']

我用了很多方法,还是改不了。

# Method 1
pop[(pop['Log GDP per capita']).isna()]['Log GDP per capita'].fillna(8,inplace=True)
# Method 2
pop['Log GDP per capita'] = pop['Log GDP per capita'].replace(np.nan,8,inplace=True)
# Method 3
pop[(pop['Log GDP per capita'].isna())][(pop['Country name'])=='Somalia']['Log GDP per capita'].replace(np.nan,7.6,inplace=True)
# Method 4
pop[(pop['Log GDP per capita'].isna())][(pop['Country name'])=='Somalia'].mask(pop['Log GDP per capita']=='', 7.946, inplace=True)
# Method 5
pop[(pop['Log GDP per capita'].isna())][(pop['Country name'])=='Somalia'].mask(pop['Log GDP per capita']==pd.np.nan, 7.946, inplace=True)
# Method 6
pop[(pop['Log GDP per capita'].isna())][(pop['Country name'])=='Somalia'].mask(pop['Log GDP per capita']==np.nan, 7.946, inplace=True)
# Method 7
pop.loc([(pop['Country name']=='Somalia')]['Log GDP per capita'])=7.946 

我该如何改进?

Kaggle Notebook

最佳答案

使用.loc:

mask = pop['Log GDP per capita'].isna() & pop['Country name'].eq('Somalia')
pop.loc[mask, 'Log GDP per capita'] = 8

关于python - 如何替换 pandas 上过滤的多列中的 nan 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70918372/

相关文章:

python - 如何根据日期条件在数据集上添加行?

python - 根据列的分数使用 Python 计算并集和交集

python - 将列表更新为元组

python - 识别二维 numpy 数组中的连续区域

python - 如何比较 Pandas 中两个 DataFrame 的值?

r - 如果满足多个条件,则将值从一个数据帧复制到另一个数据帧 (R)

python - Hashicorp python 客户端 hvac 问题 :- "bad handshake: Error([(' SSL routines', 'tls_process_server_certificate' 、 'certificate verify failed'

python - 在 Pandas 中使用 SUMIF 创建新行

python - 使用 fill_diagonal() 设置 pandas.DataFrame 对角线上的值

python - 对 pandas 中的字符串进行排序