Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if values in pandas dataframe column is integer and write it to a list if not

I have a pandas dataframe with a column which could have integers, float, string etc. I would like to iterate over all the rows and check if each value is integer and if not, I would like to create a list with error values (values that are not integer)

I have tried isnumeric(), but couldnt iterate over each row and write errors to output. I tried using iterrows() but it converts all values to float.

ID     Field1
1      1.15
2      2
3      1
4      25
5      and

Expected Result:

[1.15,"and"]
like image 500
Padfoot123 Avatar asked Dec 22 '22 23:12

Padfoot123


1 Answers

If "Field1" is a column of strings, use str.isdigit (returns True for integers only) and negate:

df.loc[~df['Field1'].str.isdigit(), 'Field1'].tolist()
# ['1.15', 'and']

Alternatively, if the column contains mixed types, use

df.loc[~df['Field1'].astype(str).str.isdigit(), 'Field1'].tolist()
# [1.15, 'and']
like image 56
cs95 Avatar answered May 11 '23 23:05

cs95