6

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"]
3
  • Could you show what df['Field1'].tolist() looks like for this DataFrame please? May 21, 2019 at 17:23
  • I ask because the solution depends on whether the data is all strings or the column has mixed dtypes. May 21, 2019 at 17:27
  • all are strings
    – Padfoot123
    May 21, 2019 at 17:28

1 Answer 1

14

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']
9
  • 1
    Works really well.
    – prosti
    May 21, 2019 at 17:36
  • @prosti Thank you. I felt it was worth confirming the dtype of OP's data so we could find them a working solution quickly :) May 21, 2019 at 17:37
  • But it must be string = dtype('object') for that column since we deal with strings in that column. ;) else I am unaware something else may came in like dtype complex.
    – prosti
    May 21, 2019 at 17:39
  • @prosti object is a broad sweeping generalisation for anything that isn't scalar. This includes strings as well as mixed types. If they are strings, you can directly find a solution. Otherwise you would need to convert them to string first to have the string methods actually return useful results on them. May 21, 2019 at 17:41
  • Thanks Guys.. I am getting error - bad operand type for unary ~: 'float'
    – Padfoot123
    May 21, 2019 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.