0

I want to verify that values in a CSV are integers and report an error if they are not. Being an amateur, I thought I had it figured out if the user entered '8k' or whatever as a value by using this:

    try:
        int(value)
    except ValueError:
        print("No Deal, Howie!")

I completely overlooked the possibility that a user can enter 8.8, which is unacceptable as well. Unfortunately, I can't use:

if type(value) == int

because pandas dataframe turns all the ints in my CSV into numpy.float64. What can I do about this?

Milan
  • 1,743
  • 2
  • 13
  • 36
blindside044
  • 446
  • 1
  • 7
  • 20
  • 1
    When using `.read_csv`, there is a dtype parameter to specify the column types. – Trenton McKinney Jul 23 '20 at 23:15
  • Does this answer your question? [How to check if float pandas column contains only integer numbers?](https://stackoverflow.com/questions/49249860/how-to-check-if-float-pandas-column-contains-only-integer-numbers) – Craig Jul 23 '20 at 23:20
  • You asked almost this same question yesterday. https://stackoverflow.com/questions/63043034/check-all-items-in-csv-column-except-one-python-pandas Didn't the answers to that question work for you? – Craig Jul 23 '20 at 23:24
  • 1
    Unofortunately, none of those answered my question, Craig. Just left me more confused. Buuuuut, the .is_integer() worked! So thank you Alollz :) ...I couldn't seem to find that link in my google searches Craig, but thanks for the link. – blindside044 Jul 23 '20 at 23:35

4 Answers4

1

Here's a pretty safe method that will capture a bunch of different integer types.

import numpy as np

def num_is_int(x):
    if isinstance(x, (int, np.integer)):
        return True
    else:
        try:
            return x.is_integer()
        except AttributeError:
            return False

num_is_int(7)
True

num_is_int(7.0)
True

num_is_int(np.int16(7))
True

num_is_int(7.1)
False

num_is_int('7')
False

num_is_int(None)
False
ALollz
  • 57,915
  • 7
  • 66
  • 89
0

You can use int() like this:

if value == int(value)
Red
  • 26,798
  • 7
  • 36
  • 58
0

To check if the value is an integer you can convert it into a string, use .split() method and search for zeros.

An example:

A=5.000006
print(A)

B=str(A).split(sep='.')
print(B)
print(B[1])
integer=1

for b in B[1]:#B[1] is the decimal part of A
    if b!='0':
        integer=0

If integer=0, this is not an integer, If integer=1 this is an integer.

0

I would use Python's builtin isinstance function. Like this:

if not isinstance(value, int):
    print("No Deal, Howie!")
Keiron Stoddart
  • 328
  • 3
  • 12