I have an array A. I would like to divide the non-zero elements and obtain a new array B. The desired output is attached.
import numpy as np
A=np.array([[0,1,2],[4,0,8],[7,5,0]])
print([A])
The desired output is
B=[array([[0,1/1,1/2],[1/4,0,1/8],[1/7,1/5,0]])]
With NumPy arrays, it's simple:
A = np.array([[0,1,2],[4,0,8],[7,5,0]])
# Create an array with zeroes with the same shape as A
B = np.zeros(A.shape)
# Update elements in B that are non-zero in A
B[A != 0] = 1/A[A != 0]
Using numpy.where (you will get a RuntimeWarning though):
B = np.where(A, 1/A, 0)
or numpy.divide:
B = np.divide(1, A, out=np.zeros_like(A, dtype=float), where=A!=0)
Try this :
try:
B = A/2
except:
pass
Related
I have the following prior_total built from prior_fish array and np.arange(5) with num_prior_loop=50
# Declare prior array
prior_start = 1
prior_end = 5
prior_fish = np.logspace(prior_start,prior_end,num_prior_loop)
# Prior total
prior_total = np.stack([prior_fish.T, np.arange(5)])
How to get access to prior_total[i,j], I mean i for the i-th element of prior_fish and j for the j-element of np.aranage(5) ?
I tried : prior_total[i,j] and prior_total([[[0,i],[1,j]]] but this doesn't work.
What might be wrong here?
a = np.logspace(1,5,5)
b = np.arange(5)
c = np.stack([a.T, b])
c[i,j] returns a single element, at col i row j
c[0,i], c[1,j] returns two elements, the ith element of a and the jth element of b
Given two ndarrays a = np.asarray([[0,1,2],[3,4,5]]) and b = np.asarray([[6,7,8],[9,10,11]])I want to write a function that iterates over a and b, such that
[0,1,2] and [6,7,8] are considered
[3,4,5] and [9,10,11] are considered
An example would be a functionn that takes
[0,1,2] and [6,7,8] as an input and outputs 0*6+1*7+2*8 = 23
[3,4,5] and [9,10,11] as an input and outputs 3*9+4*10+5*11 = 122
-> (23,122)
Is there any way to do this efficiently in numpy?
My idea was to zip both arrays, however, this is not efficient.
Edit: I am looking for a way to apply a customizable function myfunc(x,y). In the previous example myfunc(x,y) corresponded to the multipication.
c = a * b
sum1 = c[0].sum()
sum2 = c[1].sum()
if you want the algorithmic way ( custom function )
a = np.asarray([[0,1,2],[3,4,5]])
b = np.asarray([[6,7,8],[9,10,11]])
for i in range(a.shape[0]) :
s = 0
for j in range(a.shape[1]) :
s = s + a[i][j]*b[i][j]
print(s)
import numpy as np
a = np.asarray([[0,1,2],[3,4,5]])
b = np.asarray([[6,7,8],[9,10,11]])
c = a*b
print(sum(c[0]),sum(c1))
ans->23,122
Don't need to use zip both array, you need to understand numpy package help you work well with matrix. So you need the basic knowledge about matrix, i recommend you learn from this link http://cs231n.github.io/python-numpy-tutorial/ , from cs231n of Stanford university.
This is a function can solve your problem:
import numpy as np
def interates(matrix_a, matrix_b):
product = matrix_a*matrix_b
return (np.sum(product,1))
The value product contain a new matrix with same shape of matrix_a and matrix_b, each element in there is the result of matrix_a[i][j] * matrix_b[i][j]with i and j run from 0 to matrix_a.shape[0]and matrix_a.shape[1].
Now check with your example
a = np.asarray([[0,1,2],[3,4,5]])
b = np.asarray([[6,7,8],[9,10,11]])
result = interates(a,b)
Print result
>> print(result)
>> [23 122]
If you want a tuple
>> result = tuple(result)
>> print(result)
>> (23, 122)
I have a 1D vector Zc containing n elements that are 2D arrays. I want to find the index of each 2D array that equals np.ones(Zc[i].shape).
a = np.zeros((5,5))
b = np.ones((5,5))*4
c = np.ones((5,5))
d = np.ones((5,5))*2
Zc = np.stack((a,b,c,d))
for i in range(len(Zc)):
a = np.ones(Zc[i].shape)
b = Zc[i]
if np.array_equal(a,b):
print(i)
else:
pass
Which returns 2. The code above works and returns the correct answer, but I want to know if there a vectorized way to achieve the same result?
Going off of hpaulj's comment:
>>> allones = (Zc == np.array(np.ones(Zc[i].shape))).all(axis=(1,2))
>>> np.where(allones)[0][0]
2
I am new to programming and had a question. If I had two numpy arrays:
A = np.array([[1,0,3], [2,6,5], [3,4,1],[4,3,2],[5,7,9]], dtype=np.int64)
B = np.array([[3,4,5],[6,7,9],[1,0,3],[4,5,6]], dtype=np.int64)
I want to compare the last two columns of array A to the last two columns of array B, and then if they are equal, output the entire row to a new array. So, the output of these two arrays would be:
[1,0,3
1,0,3
5,7,9
6,7,9]
Because even though the first element does not match for the last two rows, the last two elements do.
Here is my code so far, but it is not even close to working. Can anyone give me some tips?
column_two_A = A[:,1]
column_two_B = B[:,1]
column_three_A = A[:,2]
column_three_B = B[:,2]
column_four_A = A[:,3]
column_four_B = B[:,3]
times = A[:,0]
for elementA in column_three_A:
for elementB in column_three_B:
if elementA == elementB:
continue
for elementC in column_two_A:
for elementD in column_two_B:
if elementC == elementD:
continue
for elementE in column_four_A:
for elementF in column_four_B:
if elementE == elementF:
continue
element.append(time)
print(element)
Numpy holds many functions for that kind of tasks. Here is a solution to check if the values of A are in B. Add print() statements and check what chk, chk2 and x are.
import numpy as np
A = np.array([[1,0,3], [2,6,5], [3,4,1],[4,3,2],[5,7,9]], dtype=np.int64)
B = np.array([[3,4,5],[6,7,9],[1,0,3],[4,5,6]], dtype=np.int64)
c = []
for k in A:
chk = np.equal(k[-2:], B[:, -2:])
chk2 = np.all(chk, axis=1)
x = (B[chk2, :])
if x.size:
c.append(x)
print(c)
I think I figured it out by staying up all night... thank you!
`for i in range(len(A)):
for j in range(len(B)):
if A[i][1] == B[j][1]:
if A[i][2] == B[j][2]:
print(B[j])
print(A[i])`
I have the following two arrays with shape:
A = (d,w,l)
B = (d,q)
And I want to combine these into a 3d array with shape:
C = (q,w,l)
To be a bit more specific, in my case d (depth of the 3d array) is 2, and i'd first like to multiply all positions out of w * l in the upper layer of A (so d = 0) with the first value of B in the highest row (so d=0, q=0). For d=1 I do the same, and then sum the two so:
C_{q=0,w,l} = A_{d=0,w,l}*B_{d=0,q=0} + A_{d=1,w,l}*B_{d=1,q=0}
I wanted to calculate C by making use of numpy.einsum. I thought of the following code:
A = np.arange(100).reshape(2,10,5)
B = np.arange(18).reshape(2,9)
C = np.einsum('ijk,i -> mjk',A,B)
Where ijk refers to 2,10,5 and mjk refers to 9,10,5. However I get an error. Is there some way to perform this multiplication with numpy einsum?
Thanks
Your shapes A = (d,w,l), B = (d,q), C = (q,w,l) practically write the einsum expression
C=np.einsum('dwl,dq->qwl',A,B)
which I can test with
In [457]: np.allclose(A[0,:,:]*B[0,0]+A[1,:,:]*B[1,0],C[0,:,:])
Out[457]: True