I have a 2 dimension array and based if the value is greater than 0 I want to do a operation (example with x+1).
In plain python something like this:
a = [[2,5], [4,0], [0,2]]
for x in range(3):
for y in range(2):
if a[x][y] > 0:
a[x][y] = a[x][y] + 1
Result for a is [[3, 6], [5, 0], [0, 3]]. This is what I want.
Now I want to prevent the nested loop and tried with numpy something like this:
a = np.array([[2,5], [4,0], [0,2]])
mask = (a > 0)
a[mask] + 1
The result is now a 1 dimension and the shape of the array [3 6 5 3]. How can I do this operation and don't loose the dimension like in the plain python example before?
If a is a numpy array, you can simply do -
a[a>0] +=1
Sample run -
In [335]: a = np.array([[2,5], [4,0], [0,2]])
In [336]: a
Out[336]:
array([[2, 5],
[4, 0],
[0, 2]])
In [337]: a[a>0] +=1
In [338]: a
Out[338]:
array([[3, 6],
[5, 0],
[0, 3]])
Related
I have different sizes of arrays that each element is its index if it was flatten. Is there a way to print out every element per square going clockwise? I thought about slicing the arrays but that doesn't go clockwise and only prints one square and not all.
arr1 = np.array([[0, 1],[2, 3]])
arr2 = np.array([[0, 1, 2],[3, 4, 5]])
arr3 = np.array([[0, 1],[2, 3],[4, 5]])
print(arr1[0:2,0:2])
print()
print(arr2[0:2,0:2])
print()
print(arr3[0:2,0:2])
output:
[[0 1]
[2 3]]
[[0 1]
[3 4]]
[[0 1]
[2 3]]
Maybe this helps
import numpy as np
a = np.random.randint(0, 10, size=(7, 9))
print(a)
for i in range(a.shape[0]):
for j in range(a.shape[1]):
x = a[i:i+2, j:j+2]
if x.flatten().size == 4:
print(x) # every 2 by 2 array of 4 elements
m = x.copy() # copy x so not to be changed!
m[1] = m[1][::-1] # reverse row 1 elements
print(m.flatten()) # 1d array clockwise
from numpy.lib.stride_tricks import sliding_window_view
def zay_117(arr):
output = []
for row in sliding_window_view(arr, window_shape=(2,2)):
for sq in row:
output.append(np.hstack((sq[0, 0:2], sq[1, 0:2][::-1])).tolist())
return output
# zay_117(arr1)
# [[0, 1, 3, 2]]
# zay_117(arr2)
# [[0, 1, 4, 3], [1, 2, 5, 4]]
# zay_117(arr3)
# [[0, 1, 3, 2], [2, 3, 5, 4]]
I have this set of equations I want to perform:
x = np.linspace(0, 2, 3)
y = np.linspace(x, x+2, 3)
I then want to populate the 2D array with a calculation that does:
a = 2*x + y
So for example, given an array:
x = [0, 1, 2]
Then, the array y is:
y = [[0, 1, 2],
[1, 2, 3],
[2, 3, 4]]
When I perform the operation a = 2*x + y I should get the array:
a = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
How do I do this, keeping in mind I want to perform this operation quickly for array of size up to 10000x10000 (or larger)?
Or do your code adding two Ts:
print((2*x+y.T).T)
Output:
[[0 1 2]
[3 4 5]
[6 7 8]]
I was wondering how I would vectorize this for loop. Given a 2x2x2 array x and an array where each element is the ith, jth, and kth element of the array I want to get x[i,j,k]
Given an arrays x and y
x = np.arange(8).reshape((2, 2, 2))
y = [[0, 1, 1], [1, 1, 0]]
I want to get:
x[0, 1, 1] = 3 and x[1, 1, 0] = 6
I tried:
print(x[y])
But it prints:
array([[2, 3],
[6, 7],
[4, 5]])
So I ended up doing:
for y_ in y:
print(x[y_[0], y_[1], y_[2]])
Which works, but I can't help but think there is a better way.
Use transposed y i.e zip(*y) as the index; You need to have the indices for each dimension as an element for advanced indexing to work:
x[tuple(zip(*y))]
# array([3, 6])
for example, I have the numpy arrays like this
a =
array([[1, 2, 3],
[4, 3, 2]])
and index like this to select the max values
max_idx =
array([[0, 2],
[1, 0]])
how can I access there positions at the same time, to modify them.
like "a[max_idx] = 0" getting the following
array([[1, 2, 0],
[0, 3, 2]])
Simply use subscripted-indexing -
a[max_idx[:,0],max_idx[:,1]] = 0
If you are working with higher dimensional arrays and don't want to type out slices of max_idx for each axis, you can use linear-indexing to assign zeros, like so -
a.ravel()[np.ravel_multi_index(max_idx.T,a.shape)] = 0
Sample run -
In [28]: a
Out[28]:
array([[1, 2, 3],
[4, 3, 2]])
In [29]: max_idx
Out[29]:
array([[0, 2],
[1, 0]])
In [30]: a[max_idx[:,0],max_idx[:,1]] = 0
In [31]: a
Out[31]:
array([[1, 2, 0],
[0, 3, 2]])
Numpy support advanced slicing like this:
a[b[:, 0], b[:, 1]] = 0
Code above would fit your requirement.
If b is more than 2-D. A better way should be like this:
a[np.split(b, 2, axis=1)]
The np.split will split ndarray into columns.
I have four numpy arrays like:
X1 = array([[1, 2], [2, 0]])
X2 = array([[3, 1], [2, 2]])
I1 = array([[1], [1]])
I2 = array([[1], [1]])
And I'm doing:
Y = array([I1, X1],
[I2, X2]])
To get:
Y = array([[ 1, 1, 2],
[ 1, 2, 0],
[-1, -3, -1],
[-1, -2, -2]])
Like this example, I have large matrices, where X1 and X2 are n x d matrices.
Is there an efficient way in Python whereby I can get the matrix Y?
Although I am aware of the iterative manner, I am searching for an efficient manner to accomplish the above mentioned.
Here, Y is an n x (d+1) matrix and I1 and I2 are identity matrices of the dimension n x 1.
How about the following:
In [1]: import numpy as np
In [2]: X1 = np.array([[1,2],[2,0]])
In [3]: X2 = np.array([[3,1],[2,2]])
In [4]: I1 = np.array([[1],[1]])
In [5]: I2 = np.array([[4],[4]])
In [7]: Y = np.vstack((np.hstack((I1,X1)),np.hstack((I2,X2))))
In [8]: Y
Out[8]:
array([[1, 1, 2],
[1, 2, 0],
[4, 3, 1],
[4, 2, 2]])
Alternatively you could create an empty array of the appropriate size and fill it using the appropriate slices. This would avoid making intermediate arrays.
You need numpy.bmat
In [4]: A = np.mat('1 ; 1 ')
In [5]: B = np.mat('2 2; 2 2')
In [6]: C = np.mat('3 ; 5')
In [7]: D = np.mat('7 8; 9 0')
In [8]: np.bmat([[A,B],[C,D]])
Out[8]:
matrix([[1, 2, 2],
[1, 2, 2],
[3, 7, 8],
[5, 9, 0]])
For a numpy array, this page suggests the syntax may be of the form
vstack([hstack([a,b]),
hstack([c,d])])