franco_b franco_b - 4 months ago 18
Python Question

Pandas select only numeric or integer field from dataframe

I have this Pandas dataframe (df):

A B
0 1 green
1 2 red
2 s blue
3 3 yellow
4 b black


A type is object.

I'd select the record where A value are integer or numeric to have:

A B
0 1 green
1 2 red
3 3 yellow


Thanks

Answer

Call apply on the dataframe (note the double square brackets df[['A']] rather than df['A']) and call the string method isdigit(), we then set param axis=1 to apply the lambda function row-wise. What happens here is that the index is used to create a boolean mask.

In [66]:
df[df[['A']].apply(lambda x: x[0].isdigit(), axis=1)]
Out[66]:
       A       B
Index           
0      1   green
1      2     red
3      3  yellow
Comments