Python 熊猫系列中字符串的过滤器

Python 熊猫系列中字符串的过滤器,python,pandas,Python,Pandas,有没有比这更好的方法来过滤熊猫系列中的字符串 以下是我的想法: df = pd.DataFrame({'a': [1,2,3,4,'cat','hat','mat'], 'b': [1,2,3,4,5,6,7] }) 原件: a b 0 1 1 1 2 2 2 3 3 3 4 4 4 cat 5 5 hat 6 6 mat 7 df = df[df['a'].apply(lambda x: isinstance(x, str))] 结果: a

有没有比这更好的方法来过滤熊猫系列中的字符串

以下是我的想法:

df = pd.DataFrame({'a': [1,2,3,4,'cat','hat','mat'], 'b': [1,2,3,4,5,6,7] })
原件:

a   b
0   1   1
1   2   2
2   3   3
3   4   4
4   cat 5
5   hat 6
6   mat 7

df = df[df['a'].apply(lambda x: isinstance(x, str))]
结果:

a   b
4   cat 5
5   hat 6
6   mat 7
但是,这种语法似乎很冗长。有这种形式的东西吗

df[df['a'].is_type(str)] 

编辑:我感兴趣的是检查类型,而不是内容。因此,例如,我想包括
'12345'
并排除
12345

,我将向您推荐
。\u numeric

df[pd.to_numeric(df.a,errors='coerce').isna()]
Out[246]: 
     a  b
4  cat  5
5  hat  6
6  mat  7
<0>如果你考虑评论中提到的情况为零

df[df.a.map(lambda x : type(x).__name__)=='str']
Out[257]: 
     a  b
4  cat  5
5  hat  6
6  mat  7
您也可以尝试:

df[df.a.str.isalpha() == True]
输出:


OP是否要筛选
'1'
字符串?这会过滤掉它,我不确定OP想要什么。不,我感兴趣的是检查类型,而不是内容。因此,我想包括
'12345'
并排除
12345
。我将编辑问题来解释这一点。
df[df.a.apply(type)==str]
有效吗?是的-这是一个好主意,绝对更简洁。请尝试isallnum()==True它可以解释像“123”这样的字符串
     a  b
4  cat  5
5  hat  6
6  mat  7