如何按条件删除列?

3 投票
2 回答
3973 浏览
提问于 2025-04-17 15:39

假设 df 是一个 pandas 的 DataFrame 对象。

我该如何删除 df 中所有只包含 None、空字符串或仅包含空格的字符串的列呢?

删除的标准可以这样理解:那些列中的所有值经过下面这个测试函数后都返回 True 的列。

lambda x: (x is None) or not re.match('\S', str(x))

2 个回答

1

我大致上弄明白了下面的内容,但我对Python中的正则表达式还不太熟悉。这是我会采取的基本方法:

示例数据:

In [1]: df
Out[1]:
      a  b  c
0  None     1
1     b     2
2     c  x  3
3     d     4
4     e  z  5

In [2]: df.to_dict()
Out[2]:
{'a': {0: None, 1: 'b', 2: 'c', 3: 'd', 4: 'e'},
 'b': {0: ' ', 1: ' ', 2: 'x', 3: ' ', 4: 'z'},
 'c': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}}

使用一个lambda函数来测试你想要删除的条件:

In [3]: df.apply(lambda x: x.isin([None,""," "]))
Out[3]:
       a      b      c
0   True   True  False
1  False   True  False
2  False  False  False
3  False   True  False
4  False  False  False

调用any()方法,这个方法会检查数据框中是否有任何列满足条件为真:

In [4]: df.apply(lambda x: x.isin([None,""," "])).any()
Out[4]:
a     True
b     True
c    False

用上面得到的布尔序列来索引数据框的列,以获取你想要删除的列:

In [5]: drop_cols = df.columns[df.apply(lambda x: x.isin([None,""," "])).any()]

In [6]: drop_cols
Out[6]: Index([a, b], dtype=object)

使用df.drop()方法,并传入axis=1选项,这样就可以对列进行操作:

In [7]: df.drop(drop_cols, axis=1)
Out[7]:
   c
0  1
1  2
2  3
3  4
4  5

现在如果有对Pandas或正则表达式更有经验的人能搞定那部分,我觉得你就有了一个不错的解决方案。

3

你可以使用 applymap 这个方法,把你的函数应用到 DataFrame 中的每一个元素上:

In [19]: df = pd.DataFrame({'a': [None] * 4, 'b': list('abc') + [' '],
                            'c': [None] + list('bcd'), 'd': range(7, 11),
                            'e': [' '] * 4})

In [20]: df
Out[20]: 
      a  b     c   d  e
0  None  a  None   7   
1  None  b     b   8   
2  None  c     c   9   
3  None        d  10   

In [21]: to_drop = df.applymap(
                     lambda x: (x is None) or not re.match('\S', str(x))).all()

In [22]: df.drop(df.columns[to_drop], axis=1)
Out[22]: 
   b     c   d
0  a  None   7
1  b     b   8
2  c     c   9
3        d  10

撰写回答