3

As the title says, it is not about type of elements. I need to be sure that the values of elements are integers, i.e.

np.array([1, 2, 3])
np.array([1., 2.0, 9/3])

must both give [True, True, True] after the 'Are they integers?'-checking.

Is there a clean and pythonic/numpyic way of doing this?

I've tried some many-lines-combinations such as:

isinstance(x, (int, np.integer)) 
#or
(1.0).is_integer()

but they are cumbersome and ugly.

Grayrigel
  • 3,474
  • 5
  • 14
  • 32
user7647857
  • 369
  • 2
  • 9
  • I've made some progress in this regard. There is a standalone numpy function now available. Let's see if it makes it to numpy. – Mad Physicist Dec 31 '21 at 01:24

3 Answers3

3

What I use is this quantity % int(quantity) == 0

2

One More Way:

>>> x = np.array([1.,2.0,9/3])
>>> [not (i%1) for i in x]
[True, True, True]
1

Here is a oneliner using is_integer():

>>> x = np.array([1., 2.0, 9/3])
>>> all([i.is_integer() for i in x])
True
Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Grayrigel
  • 3,474
  • 5
  • 14
  • 32
  • I have added one line solution using `is_integer()`, which is not cumbersome. – Grayrigel Sep 24 '20 at 10:59
  • `all(i.is_integer() for i in x)` is 'more correct'. remove the [] and it will be faster (i.e. stop at the first non integer encounter). There is no point in creating a temporary list. – Andreas H. Mar 08 '23 at 12:56