HancokCX
HancokCX

Reputation: 3

round a number to a range of numbers Python

I have two arrays: X = np.linspace(0,100,101) and Y = np.linspace(0,100,15). How to make the values of one array be rounded to the values of the other array. that is, I finally have an array of size 101 but the values of the array X came close to the nearest values of the array Y.

Upvotes: 0

Views: 332

Answers (2)

Alexander Skakun
Alexander Skakun

Reputation: 15

The simplest way is to use X array to produse Y array. Like this:

Y = X[::len(X)//15]

But it'll give you a little biased numbers.

For this particular case you also can use simple round function:

Y = np.array(list(map(round, Y)))

In general, you can solve this by searching for the minimal difference between elements in arrays:

Y = X[[abs(X-i).argmin() for i in Y]]

Upvotes: 1

sams-studio
sams-studio

Reputation: 733

Like this?

Y[np.absolute(X[:,np.newaxis]-Y).argmin(axis=1)]

Upvotes: 1

Related Questions