pandas dataframe删除常量列

use*_*143 28 python dataframe pandas

我有一个数据框,可能有也可能没有相同值的列.例如

    row    A    B
    1      9    0
    2      7    0
    3      5    0
    4      2    0
Run Code Online (Sandbox Code Playgroud)

我想回来

   row    A  
   1      9    
   2      7    
   3      5    
   4      2
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法来识别是否存在这些列中的任何一列然后将其删除?

cht*_*mon 42

我相信这个选项会比这里的其他答案更快,因为如果找到非唯一值,它只会遍历数据帧一次以进行比较和短路.

>>> df

   0  1  2
0  1  9  0
1  2  7  0
2  3  7  0

>>> df.loc[:, (df != df.iloc[0]).any()] 

   0  1
0  1  9
1  2  7
2  3  7
Run Code Online (Sandbox Code Playgroud)


DSM*_*DSM 21

NaN像往常一样忽略s,如果是,则列是常量nunique() == 1.所以:

>>> df
   A  B  row
0  9  0    1
1  7  0    2
2  5  0    3
3  2  0    4
>>> df = df.loc[:,df.apply(pd.Series.nunique) != 1]
>>> df
   A  row
0  9    1
1  7    2
2  5    3
3  2    4
Run Code Online (Sandbox Code Playgroud)

  • 至少在 Pandas 0.20.3 中,`df.apply(pd.Series.nunique)` 更简单,是 `df.nunique()`。 (2认同)

Yan*_*uru 5

我在大小为120 * 10000的数据帧上比较了各种方法。并发现有效的是

def drop_constant_column(dataframe):
    """
    Drops constant value columns of pandas dataframe.
    """
    return dataframe.loc[:, (dataframe != dataframe.iloc[0]).any()]
Run Code Online (Sandbox Code Playgroud)

1循环,最佳为3:每个循环237毫秒

其他竞争者是

def drop_constant_columns(dataframe):
    """
    Drops constant value columns of pandas dataframe.
    """
    result = dataframe.copy()
    for column in dataframe.columns:
        if len(dataframe[column].unique()) == 1:
            result = result.drop(column,axis=1)
    return result
Run Code Online (Sandbox Code Playgroud)

1个循环,最佳3:每个循环19.2 s

def drop_constant_columns_2(dataframe):
    """
    Drops constant value columns of pandas dataframe.
    """
    for column in dataframe.columns:
        if len(dataframe[column].unique()) == 1:
            dataframe.drop(column,inplace=True,axis=1)
    return dataframe
Run Code Online (Sandbox Code Playgroud)

1个循环,最佳3:每个循环317毫秒

def drop_constant_columns_3(dataframe):
    """
    Drops constant value columns of pandas dataframe.
    """
    keep_columns = [col for col in dataframe.columns if len(dataframe[col].unique()) > 1]
    return dataframe[keep_columns].copy()
Run Code Online (Sandbox Code Playgroud)

1个循环,最佳3:每个循环358毫秒

def drop_constant_columns_4(dataframe):
    """
    Drops constant value columns of pandas dataframe.
    """
    keep_columns = dataframe.columns[dataframe.nunique()>1]
    return dataframe.loc[:,keep_columns].copy()
Run Code Online (Sandbox Code Playgroud)

1个循环,最佳3:每个循环1.8 s