0
import numpy as np 
import sklearn 
import sklearn.datasets
from sklearn import svm
x = np.array([1,3,67,8])
print(x)
print(type(x))

if type(x) != int:
    y = x.astype(int)
    print(y)
    print(type(y))
else:
    print ("X is already an integer")

This is my code here if x is not integer then convert it to integer else print it as integer but it works weirdly that code in if statement is executed even if x is integer or float.

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • What is the output you actually get? What is the output you expected? And please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Feb 04 '18 at 11:41
  • 5
    You should avoid doing `type(x) == int` and instead use `isinstance(x, int)` – match Feb 04 '18 at 11:42
  • The issue is "if type(x) != int:" , it can be true to any other data type other than int . – Avinash Bakshi Feb 04 '18 at 11:53
  • This is a guess, but I think user wants to check if the entries in `x` are integers. In this case, checking for type isn't the right way, since you can have "integer" values in a `float` array. – jpp Feb 04 '18 at 11:58

1 Answers1

1

I believe this is what you are looking for. To check whether a value is an integer (even if in a float array), then you can test x == int(x).

import numpy as np 

arr = np.array([1, 3, 67, 8, 7.5])

print(arr, type(arr))

for x in arr:
    if x != int(x):
        y = x.astype(int)
        print(y, type(y))
    else:
        print(str(int(x)) + ' is already an integer')

# [  1.    3.   67.    8.    7.5] <class 'numpy.ndarray'>
# 1 is already an integer
# 3 is already an integer
# 67 is already an integer
# 8 is already an integer
# 7 <class 'numpy.int32'>
jpp
  • 159,742
  • 34
  • 281
  • 339