gpt4 book ai didi

python - 如何按条件删除列?

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:02 25 4
gpt4 key购买 nike

假设 df 是一个 pandas DataFrame 对象。

How do I drop all the columns of df that contain only None, empty strings, or white-space-only strings?

丢弃的标准可以表示为当将所有值提供给以下测试函数时所有值都产生 True 的那些列:

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

最佳答案

您可以使用 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

关于python - 如何按条件删除列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14838945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com