0

I make an array:

X = np.arange(0.001, 1, 0.001)

Later I want to find the points in X that match a value I pull and format from a dataframe x1:

index1 = np.where(X == x1)

I've looked at this post, but:

  1. np.arange produces an array
  2. x1 is an array

I'm left very confused.

I tried it on a scratch pad in PyCharm:

import numpy as np
precision = 3
delta = 10 ** -precision
a = np.arange(delta, 1, delta)
n = np.array([0.070])

print(np.where(a == n))

If n equals 0.071, 0.072, 0.073, it returns an empty cell. Many values of n give me a value and very few produce an error from an empty array.

I want to find all the values I need.

Thanks.

alan.elkin
  • 954
  • 1
  • 10
  • 19
Digeridoo
  • 3
  • 1

2 Answers2

4

Never* use == to compare floating point values. Choose a precision value you are comfortable with and check they are within that distance.

Luckily numpy has a convenient way of doing this: np.isclose.

>>> print(np.where(np.isclose(a, n)))
(array([69], dtype=int64),)

Once you have read and understood this you may use == on floating point values when appropriate.

orlp
  • 112,504
  • 36
  • 218
  • 315
0

Building on what @orlp said, you are generating floating point numbers using the np.arrange() function. As you can see below, the number is close to 0.073 but not exactly 0.073.

import numpy as np
precision = 3
delta = 10 ** -precision
a = np.arange(delta, 1, delta)
n = np.array([0.073])
print(a[72]) #
print(n)
print(a[72] == n[0])

gives the output of

0.07300000000000001
[0.073]
False

nagoldfarb
  • 66
  • 11
  • I see. The value I am looking for in X is formatted to 3 decimals, but not the array itself. Is there a way to produce an array of formatted values? – Digeridoo Jun 05 '20 at 08:37
  • You can use `np.round(a,4)` I dont know how optimal this solution it should work. – nagoldfarb Jun 05 '20 at 12:14