查找至少包含一行字母的列

时间:2019-07-01 14:20:41

标签: python pandas

假设我有以下数据集:

import pandas as pd

df = pd.DataFrame(
        {'A': [1, 2, 3],
         'B': ['one', 2, 3],
         'C': [4, 5, '6Y']
         })

我想找出-无需繁琐的for循环-哪些列包含至少一个带有字母字母的情况(此处为BC)。我猜结果应该是布尔值列表或索引。

谢谢您的帮助!

3 个答案:

答案 0 :(得分:5)

作为一种快速简单的解决方案,您可以使用replace并进行过滤:

df.replace('(?i)[a-z]', '', regex=True).ne(df).any()

A    False
B     True
C     True
dtype: bool

df.columns[df.replace('(?i)[a-z]', '', regex=True).ne(df).any()]
# Index(['B', 'C'], dtype='object')

另一种选择是逐列应用str.contains

mask = df.astype(str).apply(
    lambda x: x.str.contains(r'[a-z]', flags=re.IGNORECASE)).any()
mask

A    False
B     True
C     True
dtype: bool

df.columns[mask]
# Index(['B', 'C'], dtype='object')

答案 1 :(得分:5)

我们可以使用pd.to_numeric

df.apply(pd.to_numeric, errors='coerce').isna().any().tolist()
# [False, True, True]

另一种方法可能是将applymapstr.isnumeric一起使用:

(~df.astype(str).applymap(str.isnumeric).all()).tolist()
# [False, True, True]

答案 2 :(得分:3)

在这种情况下,您可以使用to_numeric

df.apply(pd.to_numeric,errors='coerce').isnull().any()
Out[37]: 
A    False
B     True
C     True
dtype: bool

更新

df.stack().str.contains('[a-zA-Z]').groupby(level=1).any()
Out[62]: 
A    False
B     True
C     True
dtype: bool