【问题标题】:Remove NaN/NULL columns in a Pandas dataframe?删除 Pandas 数据框中的 NaN/NULL 列?
【发布时间】:2012-06-07 03:30:20
【问题描述】:

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

【问题讨论】:

  • 你能接受这个答案吗?这会将问题标记为已解决并帮助其他用户。

标签: python pandas dataframe nan


【解决方案1】:

是的,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')

【讨论】:

  • 你能指定'dropna'的值吗?例如,您可以删除全为零的行吗?
  • 您可以使用 pandas io 解析器定义给定输入表中的 NaN 值为 0,或者,您可以像这样准备您的步骤:df[df==0] = np.nan ; df=df.dropna(axis=1,how='all')
  • 就地:df.dropna(axis=1,how='all',inplace=True)
  • 我使用了df=df.dropna(axis=1,how='all'),但它删除了我所有的 df 列。其他列并非完全为空。
【解决方案2】:

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

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
'''

【讨论】:

  • 这个答案不如df.dropna(..., thresh)实现这个,我们只需要计算正确的值。而且你不需要创建任何新的数据框,你只需要df.dropna(..., inplace=True)
【解决方案3】:

另一种解决方案是在非空位置创建一个具有 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)]

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

【讨论】:

    【解决方案4】:

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

    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 列。

    【讨论】:

    • 拜托,如果你回答了什么问题,至少要使用正确的指南风格,比如 pep8...另外,pandas 提供了 dropna() 函数,所以这不是一个好的答案...
    猜你喜欢
    • 2021-06-14
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2017-12-22
    • 2021-12-06
    • 2017-11-12
    • 2018-02-24
    相关资源
    最近更新 更多