round a number to a range of numbers Python - 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.

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

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]]

Related

How to iterate over a numpy matrix based on a condition of another nump array?

I have a matrix X, and the labels to each vector of that matrix as a np array Y. If the value of Y is +1 I want to multiply the vector of matrix X by another vector W. If the value of Y is -1 I want to multiply the vector of matrix X by another vector Z.
I tried the following loop:
for i in X:
if Y[i] == 1:
np.sum(np.multiply(i, np.log(w)) + np.multiply((1-i), np.log(1-w)))
elif Y[i] == -1:
np.sum(np.multiply(i, np.log(z)) + np.multiply((1-i), np.log(1-z)))
IndexError: arrays used as indices must be of integer (or boolean) type
i is the index of X, but I'm not sure how to align the index of X to the value in that index of Y.
How can I do this?
Look into np.where, it is exactly what you need:
res = np.where(Y == +1, np.dot(X, W), np.dot(X, Z))
This assumes that Y can take only value +1 and -1. If that's not the case you can adapt the script above but we need to know what do you expect as result when Y takes a different value.
Also, try to avoid explicit for loops when using numpy, the resulting code will be thousands of times faster.
While it is better to use a no-iteration approach, I think you need a refresher on basic Python iteration.
Make an array:
In [57]: x = np.array(['one','two','three'])
Your style of iteration:
In [58]: for i in x: print(i)
one
two
three
to iterate on indices use range (or arange):
In [59]: for i in range(x.shape[0]): print(i,x[i])
0 one
1 two
2 three
enumerate is a handy way of getting both indices and values:
In [60]: for i,v in enumerate(x): print(i,v)
0 one
1 two
2 three
Your previous question had the same problem (and correction):
How to iterate over a numpy matrix?

How to handle different indices with two different arrays

I have two arrays y=[0,1,1], x=[0,0,4,10,5]and a Index-array with integers that has the indices of the non-zero entrys from x I_x=[2,3,4].
And idealy I would want something like y[2]=0, y[3]=1, y[4]=1
Is there any way to do that for the general case.
I'm happy to answer further questions because I don't think this question is asked well enough.
edit:
def function(x,y):
solution = 0
for i in I:
solution = x[i] + y[i]
return solution
This is an example what I want to do, the problem is i is from I so y would be out of bounds, what I want to know is there any way to solve this problem.
Your question is still a bit unclear, but I think you are trying to produce an array which contains the sum of the nonzero elements in x with the elements in y in those positions, and you are trying to adjust it so that Ix will not be out of bounds for y. The script below does just that:
import numpy as np
def uneven_add(a, b):
return a[np.nonzero(a)] + np.hstack((b, np.zeros((a.size - b.size))))[np.nonzero(a)]
if __name__ == '__main__':
x = np.array([0,0,4,10,5])
y = np.array([0,1,1])
print(uneven_add(x,y))

Counting Values That Are Between an X and Y Coordinate

I have a whole set of data. This data is in x and y coordinates. I'm trying to write a program that counts the amount of data between x and y coordinates...
So for example, let's say I have
(3,4)
(6,3)
(7,6)
(5,5)
(6,7)
and I can only count the data where 5<x<7 and 4<y<6
Then, the coords this program would count is:
(5,5)
(7,6)
So I would get 2.
I can figure out how to do this if I only set one constraint... For example if I just had a list of 1,2,3,4,5,6,7,8 and needed to count the numbers where 3<x<7... I could do that. However, I'm having trouble figuring out how to handle this if there's two constraints.
Thank you so much!
You can use an and to state that both conditions should be satisfied. For example:
sum(5<=x<=7 and 4<=y<=6 for x,y in coord_list)
with coord_list the list of coordinates. Note that in order to satisfy the fact that the count should be 2, you should use less than or equal (<=) operators instead of less than operators (<).
This produces:
>>> coord_list = [(3,4),(6,3),(7,6),(5,5),(6,7)]
>>> sum(5<=x<=7 and 4<=y<=6 for x,y in coord_list)
2
You can obtain the list of coordinates, for instance using list comprehension:
[(x,y) for x,y in coord_list if 5<=x<=7 and 4<=y<=6]
If the number of elements in a point is arbitrary, it is better to use indexing:
[t for t in coord_list if 5<=t[0]<=7 and 4<=t[1]<=6]

Splitting array of coordinates dependent on the Y value in Python

I have an array of coordinates, and I would like to split the array into two arrays dependent on the Y value when there is a large gap in the Y value. This post: Split an array dependent on the array values in Python does it dependent on the x value, and the method I use is like this:
array = [[1,5],[3,5],[6,7],[8,7],[25,25],[26,50],.....]
n = len(array)
for i in range(n-1):
if abs(array[i][0] - array[i+1][0]) >= 10:
arr1 = array[:i+1]
arr2 = array[i+1:]
I figured that when I want to split it dependent on the Y value I could just change:
if abs(array[i][0] - array[i+1][0]) to if abs(array[0][i] - array[0][i+1])
This does not work and I get IndexError: list index out of range.
I'm quite new to coding and I'm wondering why this does not work for finding gap in Y value when it works for finding the gap in the X value?
Also, how should I go about splitting the array depending on the Y value?
Any help is much appreciated!
you have to switch to this:
array = [[1,5],[3,5],[6,7],[8,7],[25,25],[26,50]]
n = len(array)
for i in range(n-1):
if abs(array[i][1] - array[i+1][1]) >= 10:
arr1 = array[:i+1]
arr2 = array[i+1:]

Determining if a specific, ordered vector is in a list/array

I am working on some molecular dynamics using Python, and the arrays tend to get pretty large. It would be helpful to have a quick check to see if certain vectors appear in the arrays.
After searching for way to do this, I was surprised to see this question doesn't seem to come up.
In particular,
if I have something like
import numpy as np
y = [[1,2,3], [1,3,2]]
x = np.array([[1,2,3],[3,2,1],[2,3,1],[10,5,6]])
and I want to see if the specific vectors from y are present in x (not just the elements), how would I do so?
Using something like
for i in y:
if i in x:
print(i)
will simply return every y array vector that contains at least one element of i.
Thoughts?
If you want to check if ALL vectors in y are present in the array, you could try:
import numpy as np
y = [[1,2,3], [1,3,2]]
x = np.array([[1,2,3],[3,2,1],[2,3,1],[10,5,6]])
all(True if i in x else False for i in y)
# True
You don't explicitly give your expected output, but I infer that you want to see only [1, 2, 3] as the output from this program.
You get that output if you make x merely another list, rather than a NumPy array.
The best strategy will depend on sizes and numbers. A quick solution is
[np.where(np.all(x==row, axis=-1))[0] for row in y]
# [array([0]), array([], dtype=int64)]
The result list gives for each row in y a possibly empty array of positions in x where the row occurs.

Categories

Resources