applying function to vector wise to a matrix [duplicate] - python

This question already has answers here:
numpy subtract every row of matrix by vector
(3 answers)
Closed 5 years ago.
I have a 4 x 2 matrix, i.e. a numpy vector(of length 4) of numpy vectors of length two. For example a = [[1,1],[1,2],[3,5],[8,3]]
I want to subtract the vector b = [3,6] from each row.
I tried to do the following:
np.vectorize(lamda x: x-b)(a)
but i get the error ValueError:
setting an array element with a sequence.
Can somebody explain me why and how to do this the right way?

first convert them to numpy array and then subtract b from a:
a = np.asarray(a)
b = np.asarray(b)
print a - b

Related

Inserting a new entry into a 1 dimensional numpy array without distrubing other entries [duplicate]

This question already has answers here:
Insert element into numpy array
(3 answers)
Closed 9 months ago.
Consider the following: If I have a 1 dimensional array like the following
import numpy as np
x=np.array([1,2,4,5])
Say now that I have the number 3, and wish to enter it into the 3rd position of the array (or 2nd position in "python language") without distrubing other entries so that we once we call array again after the function, we obtain:
x=np.array([1,2,3,4,5])
I'm looking for some kind of, for a lack of a better word, "splicing method" involving the array x and the number 3.
Thank you!
You can use numpy.insert
numpy.insert(arr, obj, values, axis=None)
arr -> array you want your value/values inserted to
obj -> could be an integer, a slice or a sequence of values
values -> as you can imagine, the value/values you want to insert
axis -> it works also for multi-dimensional array
Here's the solved example that you have proposed:
import numpy as np
idx = 2
val = 3
x = np.array([1,2,4,5])
x = np.insert(x,idx,val,axis=0)
Here's the result
pre-insert : [1 2 4 5]
post-insert : [1 2 3 4 5]
As you can see, this method will put in the position idx=2 of the array x in the value val=3

Get element wise average of multiple arrays [duplicate]

This question already has answers here:
Calculate mean across dimension in a 2D array
(3 answers)
Closed 12 months ago.
I have a numpy.ndarray that is made up of other arrays all of the same length. For example:
array_1 = [[3,5,6.2],
[2,4.1,10],
[3,3.5,4]]
How can I get averages element wise. So as to return a single array where each element is the average of the respective elements across all the sub arrays in array_1? So it would return:
averaged_array = [2.66, 4.2, 6.733]
to obtain the average for each list in the matrix:
averaged_array = np.array(array_1).mean(axis=1)
to obtain the average for each column:
averaged_array = np.array(array_1).mean(axis=0)

How to convert an array containing arrays to only hold one array [duplicate]

This question already has answers here:
Flatten numpy array
(2 answers)
Closed 2 years ago.
My issue is this. I have an array like this :
test = array([[1],[2],[10] .... [-5]])
I want to be able to just convert this to an array that looks like this
test = [1,2,10,..., -5]
The test is a numpy array.
You can use reshape() to change the array into 1D array as:
import numpy as np
test = np.array([[1],[2],[10],[-5]])
test=test.reshape((test.shape[0],)) # test.shape[0] gives the first dimension (the number of rows)
# reshape changes test array to one dimensional array with shape (test.shape[0],)
print(test)

Fill an empty matrix and work with the rows in python [duplicate]

This question already has answers here:
Filling a 2D matrix in numpy using a for loop
(2 answers)
Closed 2 years ago.
I have a function, where I calculate a prediction with the shape 1 x 250. I do this B times. To save all predictions for the B runs I would like to fill an empty B x 250 matrix row wise. Which python method is the best to fill an empty matrix, so that I can access the rows in a simple way (for example to subtract the rows from each other)
There must be something better then the following
indx = np.argsort(y_real[:,1])
print(len(indx)) #250
hat_y_b = []
for b in range(0,B):
y_pred = function()
hat_y_b = np.append(hat_y_b, y_pred[indx,1], axis=0)
I'm not sure I understand your question fully, but here're some general tips on dealing with numpy arrays:
In general, appending things to np arrays is very slow. Instead, allocate the entire array at the start, and fill with array indexing:
import numpy as np
# first, make an array with 250 rows and B cols.
# Each col will be a single prediction vector
all_b_arr = np.zeros((250, B))
# if no lower bound is specified, it is assumed to be 0
for idx in range(B):
# This array indexing means "every row (:), column idx"
all_b_arr[:, idx] = function()

Numpy:Getting rows of array where the corresponding array has a specific value results in IndexError: boolean index did not match indexed array along [duplicate]

This question already has answers here:
How to properly mask a numpy 2D array?
(7 answers)
Closed 3 years ago.
I tried to find in stackoverflow a thread answering this question, but I could not find. Thus, if it is duplicate, please provide the link.
The use case is very common:
I have two arrays: X which contains two dimensional datapoints and y which contains labels either 0 or 1.
X has shape (307, 2)
y has shape (307, 1)
I want to have all rows in X where the corresponding row in y has value of 1.
I tried the following code:
X[y==1]
But it raises the following error:
IndexError: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1
How can I do that?
I have found the following way:
X[np.where(np.any(y==1, axis=1))]
I also found out that the reason for the above error is that y has two dimensions. The following code will work, too, and uses masking which has a better performance:
y = y.reshape(-1)
X[y==1,:]

Categories