繁体   English   中英

删除 Pandas 数据框中的 NaN/NULL 列?

[英]Remove NaN/NULL columns in a Pandas dataframe?

我在dataFrame中有一个dataFrame ,其中几个列的值都是空值。 是否有内置函数可以让我删除这些列?

是的, dropna 请参阅http://pandas.pydata.org/pandas-docs/stable/missing_data.htmlDataFrame.dropna文档字符串:

Definition: DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None)
Docstring:
Return object with labels on given axis omitted where alternately any
or all of the data are missing

Parameters
----------
axis : {0, 1}
how : {'any', 'all'}
    any : if any NA values are present, drop that label
    all : if all values are NA, drop that label
thresh : int, default None
    int value : require that many non-NA values
subset : array-like
    Labels along other axis to consider, e.g. if you are dropping rows
    these would be a list of columns to include

Returns
-------
dropped : DataFrame

要运行的特定命令是:

df=df.dropna(axis=1,how='all')

这是一个简单的函数,您可以通过传递数据帧和阈值来直接使用它

df
'''
     pets   location     owner     id
0     cat  San_Diego     Champ  123.0
1     dog        NaN       Ron    NaN
2     cat        NaN     Brick    NaN
3  monkey        NaN     Champ    NaN
4  monkey        NaN  Veronica    NaN
5     dog        NaN      John    NaN
'''

def rmissingvaluecol(dff,threshold):
    l = []
    l = list(dff.drop(dff.loc[:,list((100*(dff.isnull().sum()/len(dff.index))>=threshold))].columns, 1).columns.values)
    print("# Columns having more than %s percent missing values:"%threshold,(dff.shape[1] - len(l)))
    print("Columns:\n",list(set(list((dff.columns.values))) - set(l)))
    return l


rmissingvaluecol(df,1) #Here threshold is 1% which means we are going to drop columns having more than 1% of missing values

#output
'''
# Columns having more than 1 percent missing values: 2
Columns:
 ['id', 'location']
'''

现在创建不包括这些列的新数据框

l = rmissingvaluecol(df,1)
df1 = df[l]

PS:您可以根据您的要求更改阈值

奖励步骤

您可以找到每列缺失值的百分比(可选)

def missing(dff):
    print (round((dff.isnull().sum() * 100/ len(dff)),2).sort_values(ascending=False))

missing(df)

#output
'''
id          83.33
location    83.33
owner        0.00
pets         0.00
dtype: float64
'''

另一种解决方案是在非空位置创建一个具有 True 值的布尔数据框,然后采用至少具有一个 True 值的列。 这将删除具有所有 NaN 值的列。

df = df.loc[:,df.notna().any(axis=0)]

如果要删除至少有一个缺失 (NaN) 值的列;

df = df.loc[:,df.notna().all(axis=0)]

这种方法在删除包含空字符串、零或基本上任何给定值的列时特别有用。 例如;

df = df.loc[:,(df!='').all(axis=0)]

删除至少有一个空字符串的列。

从数据框中删除所有空列的函数:

def Remove_Null_Columns(df):
    dff = pd.DataFrame()
    for cl in fbinst:
        if df[cl].isnull().sum() == len(df[cl]):
            pass
        else:
            dff[cl] = df[cl]
    return dff 

此函数将从 df 中删除所有 Null 列。

暂无
暂无

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

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