快速删除只有一个不同值的dataframe列

2024-04-27 21:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有比下面的代码更快的方法来删除只包含一个不同值的列?

cols=df.columns.tolist()
for col in cols:
    if len(set(df[col].tolist()))<2:
        df=df.drop(col, axis=1)

对于大型数据帧来说,这是非常缓慢的。从逻辑上讲,这会计算每列中的值的数量,而事实上,在达到两个不同的值之后,它可能会停止计数。


Tags: columns数据方法代码indfforlen
3条回答

您可以使用^{}方法找出列中的所有唯一元素,对于.unique()只返回1元素的列,可以删除该元素。示例-

for col in df.columns:
    if len(df[col].unique()) == 1:
        df.drop(col,inplace=True,axis=1)

一种不会就地丢弃的方法-

res = df
for col in df.columns:
    if len(df[col].unique()) == 1:
        res = res.drop(col,axis=1)

演示-

In [154]: df = pd.DataFrame([[1,2,3],[1,3,3],[1,2,3]])

In [155]: for col in df.columns:
   .....:     if len(df[col].unique()) == 1:
   .....:         df.drop(col,inplace=True,axis=1)
   .....:

In [156]: df
Out[156]:
   1
0  2
1  3
2  2

计时结果-

In [166]: %paste
def func1(df):
        res = df
        for col in df.columns:
                if len(df[col].unique()) == 1:
                        res = res.drop(col,axis=1)
        return res

## -- End pasted text --

In [172]: df = pd.DataFrame({'a':1, 'b':np.arange(5), 'c':[0,0,2,2,2]})

In [178]: %timeit func1(df)
1000 loops, best of 3: 1.05 ms per loop

In [180]: %timeit df[df.apply(pd.Series.value_counts).dropna(thresh=2, axis=1).columns]
100 loops, best of 3: 8.81 ms per loop

In [181]: %timeit df.apply(pd.Series.value_counts).dropna(thresh=2, axis=1)
100 loops, best of 3: 5.81 ms per loop

最快的方法似乎仍然是使用unique并在列中循环的方法。

一步:

df = df[[c for c
        in list(df)
        if len(df[c].unique()) > 1]]

两个步骤:

创建具有多个不同值的列名列表。

keep = [c for c
        in list(df)
        if len(df[c].unique()) > 1]

删除不在“keep”中的列

df = df[keep]
df.loc[:,df.apply(pd.Series.nunique) != 1]

例如

In:
df = pd.DataFrame({'A': [10, 20, np.nan, 30], 'B': [10, np.nan, 10, 10]})
df.loc[:,df.apply(pd.Series.nunique) != 1]

Out:
   A
0  10
1  20
2  NaN
3  30

相关问题 更多 >