【问题标题】:How do I drop columns in a pandas dataframe based on the count of NaN如何根据 NaN 的计数在 pandas 数据框中删除列
【发布时间】:2021-03-09 17:38:37
【问题描述】:

有没有一种简单的方法来删除主要是 NaN 的列?

我有一个包含 129 列的数据框,我想删除所有具有 50% 或更大 NaN 值的列。

【问题讨论】:

标签: pandas dataframe nan drop


【解决方案1】:

你可以这样做:

将 numpy 导入为 np 将熊猫导入为 pd

# calculate the ratio of nans
nan_ratio= df.isna().mean(axis='index')
# get the columns above a threshold of nans
# here 50% or more NaNs
cols_to_drop= nan_ratio.index[nan_ratio>=0.5].to_list()
# remove the columns from the dataframe
df.drop(columns=cols_to_drop, inplace=True)
df

测试数据:

df= pd.DataFrame(
    dict(
        c1=np.random.randint(1,100, size=100), 
        c2=np.random.randint(1,30, size=100), 
        c3=np.random.randint(1,15, size=100),
        c4=np.random.randint(1,16, size=100)
    ), 
    dtype='float32'
)
df= df.where(df > 10, np.nan)

对于测试数据,上面的代码通常会删除列c3c4(取决于随机数)。

【讨论】:

    【解决方案2】:

    感谢您的帮助。我也找到了另一种方法:

    threshold = 0.25
    df = df[df.columns[df.isnull().mean() < threshold]]
    

    【讨论】:

      猜你喜欢
      • 2012-06-07
      • 2017-09-04
      • 2021-12-06
      • 2021-02-14
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多