Updating elements in multiply indexed np.arrayView of a view of a numpy array is a copy?How does database indexing work?Finding the index of an item given a list containing it in PythonMultiple Indexes vs Multi-Column IndexesAccessing the index in 'for' loops?How do I remove an element from a list by index in Python?Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?Getting the last element of a list in PythonWhat do Clustered and Non clustered index actually mean?How do I get the number of elements in a list in Python?Delete an element from a dictionary
What are the components of a legend (in the sense of a tale, not a figure legend)?
What is the largest number of identical satellites launched together?
Replace all items that are not belong to characters and numbers by ' '
Why did the metro bus stop at each railway crossing, despite no warning indicating a train was coming?
As programers say: Strive to be lazy
How can I answer high-school writing prompts without sounding weird and fake?
Non-deterministic Finite Automata | Sipser Example 1.16
Counterexample for "continuous image of closed and bounded is closed and bounded" (in normed spaces).
Anabelian geometry ~ higher category theory
Is taking modulus on both sides of an equation valid?
German characters on US-International keyboard layout
Does Lawful Interception of 4G / the proposed 5G provide a back door for hackers as well?
Area under the curve - Integrals (Antiderivatives)
Find hamming distance between two Strings of equal length in Java
correct spelling of "carruffel" (fuzz, hustle, all that jazz)
Earliest use of "rookie"?
Is Germany still exporting arms to countries involved in Yemen?
Centering subcaptions in a tikz pgfplot subfigure environment?
Why does the headset man not get on the tractor?
How do I interpret improvement in AUC ROC from the business perspective?
Effects of ~10atm pressure on engine design
Why in the below sentence dative "dem" is used instead of nominative "der"?
Why was Endgame Thanos so different than Infinity War Thanos?
Help in identifying a mystery wall socket
Updating elements in multiply indexed np.array
View of a view of a numpy array is a copy?How does database indexing work?Finding the index of an item given a list containing it in PythonMultiple Indexes vs Multi-Column IndexesAccessing the index in 'for' loops?How do I remove an element from a list by index in Python?Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?Getting the last element of a list in PythonWhat do Clustered and Non clustered index actually mean?How do I get the number of elements in a list in Python?Delete an element from a dictionary
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have a 2D numpy array and need to update a selection of elements via multiple layers of indexing. The obvious way to do this for me does not work since it seems numpy is only updating a copy of the array and not the array itself:
import numpy as np
# Create an array and indices that should be updated
arr = np.arange(9).reshape(3,3)
idx = np.array([[0,2], [1,1],[2,0]])
bool_idx = np.array([True, True, False])
# This line does not work as intended since the original array stays unchanged
arr[idx[:,0],idx[:,1]][bool_idx] = -1 * arr[idx[:,0],idx[:,1]][bool_idx]
This is the resulting output:
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
However, I expected this output:
>>> arr
array([[0, 1, -2],
[3, -4, 5],
[6, 7, 8]])
python numpy indexing
add a comment |
I have a 2D numpy array and need to update a selection of elements via multiple layers of indexing. The obvious way to do this for me does not work since it seems numpy is only updating a copy of the array and not the array itself:
import numpy as np
# Create an array and indices that should be updated
arr = np.arange(9).reshape(3,3)
idx = np.array([[0,2], [1,1],[2,0]])
bool_idx = np.array([True, True, False])
# This line does not work as intended since the original array stays unchanged
arr[idx[:,0],idx[:,1]][bool_idx] = -1 * arr[idx[:,0],idx[:,1]][bool_idx]
This is the resulting output:
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
However, I expected this output:
>>> arr
array([[0, 1, -2],
[3, -4, 5],
[6, 7, 8]])
python numpy indexing
add a comment |
I have a 2D numpy array and need to update a selection of elements via multiple layers of indexing. The obvious way to do this for me does not work since it seems numpy is only updating a copy of the array and not the array itself:
import numpy as np
# Create an array and indices that should be updated
arr = np.arange(9).reshape(3,3)
idx = np.array([[0,2], [1,1],[2,0]])
bool_idx = np.array([True, True, False])
# This line does not work as intended since the original array stays unchanged
arr[idx[:,0],idx[:,1]][bool_idx] = -1 * arr[idx[:,0],idx[:,1]][bool_idx]
This is the resulting output:
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
However, I expected this output:
>>> arr
array([[0, 1, -2],
[3, -4, 5],
[6, 7, 8]])
python numpy indexing
I have a 2D numpy array and need to update a selection of elements via multiple layers of indexing. The obvious way to do this for me does not work since it seems numpy is only updating a copy of the array and not the array itself:
import numpy as np
# Create an array and indices that should be updated
arr = np.arange(9).reshape(3,3)
idx = np.array([[0,2], [1,1],[2,0]])
bool_idx = np.array([True, True, False])
# This line does not work as intended since the original array stays unchanged
arr[idx[:,0],idx[:,1]][bool_idx] = -1 * arr[idx[:,0],idx[:,1]][bool_idx]
This is the resulting output:
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
However, I expected this output:
>>> arr
array([[0, 1, -2],
[3, -4, 5],
[6, 7, 8]])
python numpy indexing
python numpy indexing
asked Mar 23 at 13:00
smonsayssmonsays
598
598
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
We need to mask the indices with the given mask
and then index into arr
and assign new values. For indexing, we can use tuple(masked_indices)
to index or use the two columns of the index-array for integer-indexing, thus giving us two methods.
Method #1 :
arr[tuple(idx[bool_idx].T)] *= -1
Method #2 :
idx_masked = idx[bool_idx]
arr[idx_masked[:,0],idx_masked[:,1]] *= -1
Why didn't the original method work?
On LHS you were doing arr[idx[:,0],idx[:,1]][bool_idx]
, which is esssentially two steps : arr[idx[:,0],idx[:,1]]
, which under the hoods calls arr.__getitem__(indexer)
*. When indexer is a slice, the regularity of the elements allows NumPy to return a view (by modifying the strides and offset). When indexer is an arbitrary boolean mask or arbitrary array of integers, there is in general no regularity to the elements selected, so there is no way to return a view. Let's call arr[idx[:,0],idx[:,1]]
as arr2
.
In the next step, with the combined arr[idx[:,0],idx[:,1]][bool_idx]
, i.e. arr2[bool_idx]
, under the hoods it calls arr2.__setitem__(mask)
, which is implemented to modify arr2
and as such doesn't propagate back to arr
.
*Inspiration from - https://stackoverflow.com/a/38768993/.
More info on __getitem__
,__setitem__
.
Why did the methods posted in this post work?
Because both directly used the indexer
on arr
with arr.__setitem__(indexer)
that modifies arr
.
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
1
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
1
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape(3,)
and(3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape(2,)
, on which the scalar mul was done.
– fountainhead
Mar 23 at 17:25
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
add a comment |
You just need to make a small change to your own attempt -- you need to apply the boolean index array on each of your integer index expressions. In other words, this should work:
arr[idx[:,0][bool_idx],idx[:,1][bool_idx]] *= -1
(I've just moved the [bool_idx]
inside the square brackets, to apply it on the both of the integer index expressions -- idx[:,0]
and idx[:,1]
)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55313976%2fupdating-elements-in-multiply-indexed-np-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
We need to mask the indices with the given mask
and then index into arr
and assign new values. For indexing, we can use tuple(masked_indices)
to index or use the two columns of the index-array for integer-indexing, thus giving us two methods.
Method #1 :
arr[tuple(idx[bool_idx].T)] *= -1
Method #2 :
idx_masked = idx[bool_idx]
arr[idx_masked[:,0],idx_masked[:,1]] *= -1
Why didn't the original method work?
On LHS you were doing arr[idx[:,0],idx[:,1]][bool_idx]
, which is esssentially two steps : arr[idx[:,0],idx[:,1]]
, which under the hoods calls arr.__getitem__(indexer)
*. When indexer is a slice, the regularity of the elements allows NumPy to return a view (by modifying the strides and offset). When indexer is an arbitrary boolean mask or arbitrary array of integers, there is in general no regularity to the elements selected, so there is no way to return a view. Let's call arr[idx[:,0],idx[:,1]]
as arr2
.
In the next step, with the combined arr[idx[:,0],idx[:,1]][bool_idx]
, i.e. arr2[bool_idx]
, under the hoods it calls arr2.__setitem__(mask)
, which is implemented to modify arr2
and as such doesn't propagate back to arr
.
*Inspiration from - https://stackoverflow.com/a/38768993/.
More info on __getitem__
,__setitem__
.
Why did the methods posted in this post work?
Because both directly used the indexer
on arr
with arr.__setitem__(indexer)
that modifies arr
.
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
1
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
1
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape(3,)
and(3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape(2,)
, on which the scalar mul was done.
– fountainhead
Mar 23 at 17:25
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
add a comment |
We need to mask the indices with the given mask
and then index into arr
and assign new values. For indexing, we can use tuple(masked_indices)
to index or use the two columns of the index-array for integer-indexing, thus giving us two methods.
Method #1 :
arr[tuple(idx[bool_idx].T)] *= -1
Method #2 :
idx_masked = idx[bool_idx]
arr[idx_masked[:,0],idx_masked[:,1]] *= -1
Why didn't the original method work?
On LHS you were doing arr[idx[:,0],idx[:,1]][bool_idx]
, which is esssentially two steps : arr[idx[:,0],idx[:,1]]
, which under the hoods calls arr.__getitem__(indexer)
*. When indexer is a slice, the regularity of the elements allows NumPy to return a view (by modifying the strides and offset). When indexer is an arbitrary boolean mask or arbitrary array of integers, there is in general no regularity to the elements selected, so there is no way to return a view. Let's call arr[idx[:,0],idx[:,1]]
as arr2
.
In the next step, with the combined arr[idx[:,0],idx[:,1]][bool_idx]
, i.e. arr2[bool_idx]
, under the hoods it calls arr2.__setitem__(mask)
, which is implemented to modify arr2
and as such doesn't propagate back to arr
.
*Inspiration from - https://stackoverflow.com/a/38768993/.
More info on __getitem__
,__setitem__
.
Why did the methods posted in this post work?
Because both directly used the indexer
on arr
with arr.__setitem__(indexer)
that modifies arr
.
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
1
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
1
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape(3,)
and(3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape(2,)
, on which the scalar mul was done.
– fountainhead
Mar 23 at 17:25
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
add a comment |
We need to mask the indices with the given mask
and then index into arr
and assign new values. For indexing, we can use tuple(masked_indices)
to index or use the two columns of the index-array for integer-indexing, thus giving us two methods.
Method #1 :
arr[tuple(idx[bool_idx].T)] *= -1
Method #2 :
idx_masked = idx[bool_idx]
arr[idx_masked[:,0],idx_masked[:,1]] *= -1
Why didn't the original method work?
On LHS you were doing arr[idx[:,0],idx[:,1]][bool_idx]
, which is esssentially two steps : arr[idx[:,0],idx[:,1]]
, which under the hoods calls arr.__getitem__(indexer)
*. When indexer is a slice, the regularity of the elements allows NumPy to return a view (by modifying the strides and offset). When indexer is an arbitrary boolean mask or arbitrary array of integers, there is in general no regularity to the elements selected, so there is no way to return a view. Let's call arr[idx[:,0],idx[:,1]]
as arr2
.
In the next step, with the combined arr[idx[:,0],idx[:,1]][bool_idx]
, i.e. arr2[bool_idx]
, under the hoods it calls arr2.__setitem__(mask)
, which is implemented to modify arr2
and as such doesn't propagate back to arr
.
*Inspiration from - https://stackoverflow.com/a/38768993/.
More info on __getitem__
,__setitem__
.
Why did the methods posted in this post work?
Because both directly used the indexer
on arr
with arr.__setitem__(indexer)
that modifies arr
.
We need to mask the indices with the given mask
and then index into arr
and assign new values. For indexing, we can use tuple(masked_indices)
to index or use the two columns of the index-array for integer-indexing, thus giving us two methods.
Method #1 :
arr[tuple(idx[bool_idx].T)] *= -1
Method #2 :
idx_masked = idx[bool_idx]
arr[idx_masked[:,0],idx_masked[:,1]] *= -1
Why didn't the original method work?
On LHS you were doing arr[idx[:,0],idx[:,1]][bool_idx]
, which is esssentially two steps : arr[idx[:,0],idx[:,1]]
, which under the hoods calls arr.__getitem__(indexer)
*. When indexer is a slice, the regularity of the elements allows NumPy to return a view (by modifying the strides and offset). When indexer is an arbitrary boolean mask or arbitrary array of integers, there is in general no regularity to the elements selected, so there is no way to return a view. Let's call arr[idx[:,0],idx[:,1]]
as arr2
.
In the next step, with the combined arr[idx[:,0],idx[:,1]][bool_idx]
, i.e. arr2[bool_idx]
, under the hoods it calls arr2.__setitem__(mask)
, which is implemented to modify arr2
and as such doesn't propagate back to arr
.
*Inspiration from - https://stackoverflow.com/a/38768993/.
More info on __getitem__
,__setitem__
.
Why did the methods posted in this post work?
Because both directly used the indexer
on arr
with arr.__setitem__(indexer)
that modifies arr
.
edited Mar 23 at 17:50
answered Mar 23 at 14:35
DivakarDivakar
161k1498190
161k1498190
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
1
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
1
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape(3,)
and(3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape(2,)
, on which the scalar mul was done.
– fountainhead
Mar 23 at 17:25
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
add a comment |
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
1
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
1
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape(3,)
and(3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape(2,)
, on which the scalar mul was done.
– fountainhead
Mar 23 at 17:25
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
Indeed this solves the problem, thank you! Could you explain why my initial attempt did not work?
– smonsays
Mar 23 at 15:50
1
1
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
@smonsays Added few comments on it.
– Divakar
Mar 23 at 16:02
1
1
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape
(3,)
and (3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape (2,)
, on which the scalar mul was done.– fountainhead
Mar 23 at 17:25
@Divakar: If that was indeed the reason why OP's solution didn't work, all of these working solutions should fail for the same reason. For example, in your Method # 2, what you're doing is indeed advanced indexing with two integer index arrays of shape
(3,)
and (3,)
. I think the real reason why OP's solution didn't work is because the final step in OP's solution applies boolean index, and the result of boolean indexing is always a 1d array, according to the docs, with no reference back to original array. For OP, the bool indexing returned shape (2,)
, on which the scalar mul was done.– fountainhead
Mar 23 at 17:25
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
@fountainhead Yeah, wasn't exactly correct. Edited the post.
– Divakar
Mar 23 at 17:54
add a comment |
You just need to make a small change to your own attempt -- you need to apply the boolean index array on each of your integer index expressions. In other words, this should work:
arr[idx[:,0][bool_idx],idx[:,1][bool_idx]] *= -1
(I've just moved the [bool_idx]
inside the square brackets, to apply it on the both of the integer index expressions -- idx[:,0]
and idx[:,1]
)
add a comment |
You just need to make a small change to your own attempt -- you need to apply the boolean index array on each of your integer index expressions. In other words, this should work:
arr[idx[:,0][bool_idx],idx[:,1][bool_idx]] *= -1
(I've just moved the [bool_idx]
inside the square brackets, to apply it on the both of the integer index expressions -- idx[:,0]
and idx[:,1]
)
add a comment |
You just need to make a small change to your own attempt -- you need to apply the boolean index array on each of your integer index expressions. In other words, this should work:
arr[idx[:,0][bool_idx],idx[:,1][bool_idx]] *= -1
(I've just moved the [bool_idx]
inside the square brackets, to apply it on the both of the integer index expressions -- idx[:,0]
and idx[:,1]
)
You just need to make a small change to your own attempt -- you need to apply the boolean index array on each of your integer index expressions. In other words, this should work:
arr[idx[:,0][bool_idx],idx[:,1][bool_idx]] *= -1
(I've just moved the [bool_idx]
inside the square brackets, to apply it on the both of the integer index expressions -- idx[:,0]
and idx[:,1]
)
edited Mar 23 at 15:13
answered Mar 23 at 14:36
fountainheadfountainhead
1,355313
1,355313
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55313976%2fupdating-elements-in-multiply-indexed-np-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown