Related
I have a 2d numpy array that I use for indexing (by making it a tuple of two numpy arrays, see below). From that array I now want to remove all duplicate index pairs out of the original array and in a new array (it can be multiple new arrays without or one with possible duplicates if one pair occured more than twice):
>>> import numpy as np
>>> L = 2
>>> indices = tuple(np.random.randint(0, L, (2, L**2)))
>>> indices
(array([0, 1, 0, 1]), array([1, 0, 0, 0]))
What I want to get is:
indices = (array([0, 1, 0]), array([1, 0, 0]))
indices_2 = (array([1]), array([0]))
You can use:
L = 2
indices = tuple(np.random.randint(0, L, (2, L**2)))
# stack the two arrays to handle simultaneously
# one can also use the original array without converting to tuple
a = np.vstack(indices)
# array([[0, 1, 0, 1],
# [1, 0, 0, 0]])
# get unique values and indices of the first occurrences
# expand the indices to a tuple of arrays
(*indices,), idx = np.unique(a, axis=1, return_index=True)
# ((array([0, 0, 1]), array([0, 1, 0])), array([2, 0, 1]))
# remove the first occurrences to keep only the duplicates
# again, convert the 2D indices into a tuple of arrays
(*indices_2,) = np.delete(a, idx, axis=1)
# (array([1]), array([0]))
I'm trying to run a loop where I develop a mask, and then use that mask to assign various values in various rows in one array with specific values from another array. The following script works, but only when there are no duplicate values in column 0 of array y. If there are duplicates, then the mask would have an assignment made to multiple rows in y, then the error throws. Thx for any help.
x = np.zeros(shape=(100,10))
x[:,0] = np.arange(100)
# this seed = 9 produces duplicate values in column 1, which seems cause the problem
# (no issues when there are no duplicate values in column 1 of y)
y = (np.random.default_rng(9).random((10,7))*100).astype(int)
for i in range(x.shape[0]):
mask = y[:,0] == x[i,0]
y[mask,[1,3,4,6]] = x[i,[1,2,3,4]]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [219], in <cell line: 2>()
2 for i in range(x.shape[0]):
3 mask = y[:,0] == x[i,0]
----> 4 y[mask,[1,3,4,6]] = x[i,[1,2,3,4]]
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (0,) (4,)
The mask array in your example must have at least one True in each loop, because you are assigning to rows one by one in loops. You can use if condition to be sure mask contains at least one true:
1. First solution: curing the prepared loop
range_ = np.arange(y.shape[0], dtype=np.int64)
for i in range(x.shape[0]):
mask = y[:, 0] == x[i, 0]
if np.count_nonzero(mask) != 0:
true_counts = np.count_nonzero(mask)
broadcast_x = np.broadcast_to(x[i, [1, 2, 3, 4]], shape=(true_counts, 4)) # 4 is length of [1, 2, 3, 4]
broadcast_y = np.broadcast_to([1, 3, 4, 6], shape=(true_counts, 4))
y[range_[mask][:, None], broadcast_y] = broadcast_x
2. Second solution: vectorized way (the best)
Instead using loops, we can firstly find the intersection and then use advanced indexing as:
mask = np.in1d(y[:, 0], x[:, 0])
y[mask, np.array([1, 3, 4, 6])[:, None]] = 0
now, if the x[:, 0] is specified by np.arange, for assigning an array instead of zero, for creating this array, we need to take the related values from x. For doing so, at first, we select the corresponding rows by x[y[:, 0] - x[0, 0]] (in your case it can be just x[y[:, 0] because np.arange start from 0 so x[0, 0] = 0) and then apply the masks to bring out the needed values from specified rows and columns:
mask = np.in1d(y[:, 0], x[:, 0]) # rows mask for y
new_arr = x[y[:, 0] - x[0, 0]][mask, np.array([1, 2, 3, 4])[:, None]]
y[mask, np.array([1, 3, 4, 6])[:, None]] = new_arr
if it get error IndexError: arrays used as indices must be of integer (or boolean) type so we must ensure indices type are integers so we can use some code like (y[:, 0] - x[0, 0]).astype(np.int64) or np.array([1, 2, 3, 4], dtype=np.int64).
The more comprehensive code is to find the common elements' indices between the two arrays when we didn't fill the x[:, 0] by np.arange. So the code will be as:
mask = np.in1d(y[:, 0], x[:, 0])
# finding common indices
unique_values, index = np.unique(x[:, 0], return_index=True)
idx = index[np.searchsorted(unique_values, y[:, 0])]
new_arr = x[idx][mask, np.array([1, 2, 3, 4])[:, None]]
y[mask, np.array([1, 3, 4, 6])[:, None]] = new_arr
3. Third solution: indexing (just for the prepared toy example)
For the prepared example in the question, you can do this easily by advanced indexing instead the loop:
y[:, [1, 3, 4, 6]] = 0
This last code is working on your prepared data because values in y (< 100) involved in x first column (which is from 0 to 99).
or in case of assigning array instead 0:
new_arr = np.array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y[:, [1, 3, 4, 6]] = new_arr[:, None]
I am trying to merge a sliced array to a list in Python but i get an
error: ValueError: operands could not be broadcast together with shapes `(4,)` `(2,)` .
This is my code:
y = np.array([5,3,2,4,6,1])
row = y[2:6] + np.array([0,0])
I am expecting to get a 2-item shifted vector to the left and last 2 items being assigned to 0.
Numpy array works something like a matrix. So when you try to apply the addition operation to a numpy array, you're actually performing an "element-wise addition". That's why the value you add with a numpy array must be the same dimension as the numpy array. Otherwise such a value that can be broadcasted.
Notice the example to understand what I'm saying.
Adding two lists with addition sign:
>>> [1,2] + [3,4]
[1, 2, 3, 4]
Adding two numpy arrays:
>>> np.array([1,2]) + np.array([3,4])
array([4, 6])
To get your work done, use the np.append(arr, val, axis) function. Documentation
array([1, 2, 3, 4])
>>> np.append([1,2], np.array([3,4]))
array([1, 2, 3, 4])
To concatenate arrays use np.concatenate:
In [93]: y = np.array([5,3,2,4,6,1])
In [94]: y[2:6]
Out[94]: array([2, 4, 6, 1])
In [95]: np.concatenate((y[2:6], np.array([0,0])))
Out[95]: array([2, 4, 6, 1, 0, 0])
+ is concatenate for lists. For arrays is addition (numeric sum).
Your question should not have used list and array in a sloppy manner. They are different things (in python/numpy) and can produce confusing answers.
Other answers already explain why your code fail. You can do:
out = np.zeros_like(y)
out[:-2] = y[2:]
Output:
array([2, 4, 6, 1, 0, 0])
For concatenation, you will need to convert your numpy array to a list first.
row = y[2:6] + list(np.array([0,0]))
or equivalently
row = y[2:6] + np.array([0,0]).tolist()
However, if you wish to add the two (superpose a list and numpy array), then the numpy array just needs to be the same shape as y[2:6]:
In : y[2:6] + np.array([1, 2, 3, 4])
Out: array([y[2] + 1, y[3] + 2, y[4] + 3, y[5] + 4])
I have a numpy array with some elements same as others i.e. there are ties, and I am applying np.argsort to find the indices which will sort the array:
In [29]: x = [1, 2, 1, 1, 5, 2]
In [30]: np.argsort(x)
Out[30]: array([0, 2, 3, 1, 5, 4])
In [31]: np.argsort(x)
Out[31]: array([0, 2, 3, 1, 5, 4])
As can be seen here, the outputs we get by running argsort two times are identical. However, array([2, 3, 0, 5, 1, 4]) is also a completely valid output because some elements in the original array are equal. Can I make argsort return me such "randomized" outputs when there are ties in my array? If not, what is a workaround because I don't want to bias my choice of the lowest values in the array when I am picking them.
One trick would be to add uniform noise in [0,1) range and then perform argsort-ing. Adding such a noise forces sorting only within their respective bins and gives randomized sort indices restricted to those bins -
(x+np.random.rand(len(x))).argsort()
Can someone explain exactly what the axis parameter in NumPy does?
I am terribly confused.
I'm trying to use the function myArray.sum(axis=num)
At first I thought if the array is itself 3 dimensions, axis=0 will return three elements, consisting of the sum of all nested items in that same position. If each dimension contained five dimensions, I expected axis=1 to return a result of five items, and so on.
However this is not the case, and the documentation does not do a good job helping me out (they use a 3x3x3 array so it's hard to tell what's happening)
Here's what I did:
>>> e
array([[[1, 0],
[0, 0]],
[[1, 1],
[1, 0]],
[[1, 0],
[0, 1]]])
>>> e.sum(axis = 0)
array([[3, 1],
[1, 1]])
>>> e.sum(axis=1)
array([[1, 0],
[2, 1],
[1, 1]])
>>> e.sum(axis=2)
array([[1, 0],
[2, 1],
[1, 1]])
>>>
Clearly the result is not intuitive.
Clearly,
e.shape == (3, 2, 2)
Sum over an axis is a reduction operation so the specified axis disappears. Hence,
e.sum(axis=0).shape == (2, 2)
e.sum(axis=1).shape == (3, 2)
e.sum(axis=2).shape == (3, 2)
Intuitively, we are "squashing" the array along the chosen axis, and summing the numbers that get squashed together.
To understand the axis intuitively, refer the picture below (source: Physics Dept, Cornell Uni)
The shape of the (boolean) array in the above figure is shape=(8, 3). ndarray.shape will return a tuple where the entries correspond to the length of the particular dimension. In our example, 8 corresponds to length of axis 0 whereas 3 corresponds to length of axis 1.
If someone need this visual description:
There are good answers for visualization however it might help to think purely from analytical perspective.
You can create array of arbitrary dimension with numpy.
For example, here's a 5-dimension array:
>>> a = np.random.rand(2, 3, 4, 5, 6)
>>> a.shape
(2, 3, 4, 5, 6)
You can access any element of this array by specifying indices. For example, here's the first element of this array:
>>> a[0, 0, 0, 0, 0]
0.0038908603263844155
Now if you take out one of the dimensions, you get number of elements in that dimension:
>>> a[0, 0, :, 0, 0]
array([0.00389086, 0.27394775, 0.26565889, 0.62125279])
When you apply a function like sum with axis parameter, that dimension gets eliminated and array of dimension less than original gets created. For each cell in new array, the operator will get list of elements and apply the reduction function to get a scaler.
>>> np.sum(a, axis=2).shape
(2, 3, 5, 6)
Now you can check that the first element of this array is sum of above elements:
>>> np.sum(a, axis=2)[0, 0, 0, 0]
1.1647502999560164
>>> a[0, 0, :, 0, 0].sum()
1.1647502999560164
The axis=None has special meaning to flatten out the array and apply function on all numbers.
Now you can think about more complex cases where axis is not just number but a tuple:
>>> np.sum(a, axis=(2,3)).shape
(2, 3, 6)
Note that we use same technique to figure out how this reduction was done:
>>> np.sum(a, axis=(2,3))[0,0,0]
7.889432081931909
>>> a[0, 0, :, :, 0].sum()
7.88943208193191
You can also use same reasoning for adding dimension in array instead of reducing dimension:
>>> x = np.random.rand(3, 4)
>>> y = np.random.rand(3, 4)
# New dimension is created on specified axis
>>> np.stack([x, y], axis=2).shape
(3, 4, 2)
>>> np.stack([x, y], axis=0).shape
(2, 3, 4)
# To retrieve item i in stack set i in that axis
Hope this gives you generic and full understanding of this important parameter.
Some answers are too specific or do not address the main source of confusion. This answer attempts to provide a more general but simple explanation of the concept, with a simple example.
The main source of confusion is related to expressions such as "Axis along which the means are computed", which is the documentation of the argument axis of the numpy.mean function. What the heck does "along which" even mean here? "Along which" essentially means that you will sum the rows (and divide by the number of rows, given that we are computing the mean), if the axis is 0, and the columns, if the axis is 1. In the case of axis is 0 (or 1), the rows can be scalars or vectors or even other multi-dimensional arrays.
In [1]: import numpy as np
In [2]: a=np.array([[1, 2], [3, 4]])
In [3]: a
Out[3]:
array([[1, 2],
[3, 4]])
In [4]: np.mean(a, axis=0)
Out[4]: array([2., 3.])
In [5]: np.mean(a, axis=1)
Out[5]: array([1.5, 3.5])
So, in the example above, np.mean(a, axis=0) returns array([2., 3.]) because (1 + 3)/2 = 2 and (2 + 4)/2 = 3. It returns an array of two numbers because it returns the mean of the rows for each column (and there are two columns).
Both 1st and 2nd reply is great for understanding ndarray concept in numpy. I am giving a simple example.
And according to this image by #debaonline4u
https://i.stack.imgur.com/O5hBF.jpg
Suppose , you have an 2D array -
[1, 2, 3]
[4, 5, 6]
In, numpy format it will be -
c = np.array([[1, 2, 3],
[4, 5, 6]])
Now,
c.ndim = 2 (rows/axis=0)
c.shape = (2,3) (axis0, axis1)
c.sum(axis=0) = [1+4, 2+5, 3+6] = [5, 7, 9] (sum of the 1st elements of each rows, so along axis0)
c.sum(axis=1) = [1+2+3, 4+5+6] = [6, 15] (sum of the elements in a row, so along axis1)
So for your 3D array,