franco_b franco_b - 1 year ago 169
Python Question

Pandas select only numeric or integer field from dataframe

I have this Pandas dataframe (df):

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:

0 1 green
1 2 red
3 3 yellow


Answer Source

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)]
       A       B
0      1   green
1      2     red
3      3  yellow
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download