I am looking to have two different views of the same data with the rows in a different order such that changes done through one view will be reflected in the other. Specifically, the following code
# Create original array
A = numpy.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
B = A.view()[[0, 2, 1], :] # Permute the rows
print("(before) B =\n", B)
# Change a value in A
A[1, 2] = 143
print("(after) A =\n", A)
print("(after) B =\n", B)
has the following output:
(before) B =
[[0 1 2]
[6 7 8]
[3 4 5]]
(after) A =
[[ 0 1 2]
[ 3 4 143]
[ 6 7 8]]
(after) B =
[[0 1 2]
[6 7 8]
[3 4 5]]
but I would like the last bit of that to be
(after) B =
[[0 1 2]
[6 7 8]
[3 4 143]]
Answers to this question state that getting a view at specific indices is not possible, though the OP for that question is asking about a subset of the array, whereas I would like a view of the entire array. (It seems that the key difference here is slicing vs. smart indexing)
A different post asking about slicing by rows and then columns vs columns and then rows has an accepted answer that states "All that matters is whether you slice by rows or by columns...". So I tried dealing with a flattened view of the array..
A = numpy.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
B = A.view()
B.shape = (A.size,)
A[1, 2] = 198
print("(After first) A =\n", A)
print("(After first) B =\n", B)
# Identity index map
all_idx = numpy.arange(A.size).reshape(A.shape)
# Swapped and flattened index map
new_row_idx = all_idx[[0, 2, 1]].flatten()
C = B[new_row_idx]
print("(Before second) C =\n", C)
# Manipulate through 'B'
B[7] = 666
print("(After second) B =\n", B)
print("(After second) C =\n", C)
which gives the following output:
(After first) A =
[[ 0 1 2]
[ 3 4 198]
[ 6 7 8]]
(After first) B =
[ 0 1 2 3 4 198 6 7 8]
(Before second) C =
[ 0 1 2 6 7 8 3 4 198]
(After second) B =
[ 0 1 2 3 4 198 6 666 8]
(After second) C =
[ 0 1 2 6 7 8 3 4 198]
As you can see, the 4th entry of C
is unaltered. The suggested solution to the first post I mentioned is to create a copy, make changes, and then update the original array. I can write functions to wrap this, but this doesn't eliminate the number of times I will be making copies. All it does is hide it from the user.
What am I missing here? Should I be using the data
attribute of these arrays? If so, what is a good starting point for understanding how to do this?