• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: NumPy array shape mismatch on masking/assignment command

Resolved: NumPy array shape mismatch on masking/assignment command

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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.

Answer:

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
2. Second solution: vectorized way (the best)
Instead using loops, we can firstly find the intersection and then use advanced indexing as:
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:
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:
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:
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:

If you have better answer, please add a comment about this, thank you!

numpy python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: The ‘Access-Control-Allow-Origin’ header contains multiple values ‘*, *’, but only one is allowed. cors error not resolving

02/04/2023

Resolved: SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘crm.email’ doesn’t exist (Connection: mysql, SQL: select count(*) as aggregate from `email`

02/04/2023

Resolved: Regex: Curly braces in reverse? Match X characters before a string?

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.