Filter for strings in Pandas series

Viewed 66

Is there a better way than this to filter for strings in a Pandas series?

Here's what I came up with:

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

Original:

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))]

Result:

a   b
4   cat 5
5   hat 6
6   mat 7

However, this syntax seems verbose. Is there something of the form? :

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

EDIT: I'm interested in checking for type, not content. So, for example, I would like to include '12345' and exclude 12345.

2 Answers

I will recommend to_numeric

df[pd.to_numeric(df.a,errors='coerce').isna()]
Out[246]: 
     a  b
4  cat  5
5  hat  6
6  mat  7

If you consider the situation mentioned in comment by zero

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

Also you can try:

df[df.a.str.isalpha() == True]

Out:

     a  b
4  cat  5
5  hat  6
6  mat  7
Related