【问题标题】:How to drop rows in python based on null values如何根据空值在python中删除行
【发布时间】:2020-09-07 21:13:26
【问题描述】:

您好:我有以下代码可以计算一列中空值的数量:

df_null = df.columns[df.isnull().any()]

df[df_null].isnull().sum()

结果是一个带有列名和空值个数的索引:

col1 10  
col2 20  
col3 30  

我想要做的是删除列中空值少于 15 个的所有行/记录。我已经手动浏览了这些列并使用以下内容删除了行/记录:

df.dropna(subset=['col_name'], axis=0, inplace=True)

效果很好。但我想做的是自动化这个过程,这样我就不必手动遍历每一列并手动删除空行/记录。

谢谢。

【问题讨论】:

  • 感谢您在表单代码方面分享您的努力,您能否在您的问题中发布输入和预期输出示例,然后让我们知道。这将使我们更清楚地了解问题欢呼

标签: python pandas null


【解决方案1】:

检查

s = df.isnull().sum()
dfnew = df.loc[:, (s>15)|(s==0)]
# the first condition will keep column with more than 15 null, then second , will keep all column without have NaN

【讨论】:

    【解决方案2】:

    另一种方式

    只保留至少有 n non-NaN 值的列

    n=len(df)-15
    
    
     df.dropna(thresh=n, axis=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2022-10-06
      • 2015-11-14
      相关资源
      最近更新 更多