I tried implementing a function to swap the rows of a numpy array, but it does not seem to work
This is the code:
def SwapRows(M: np.ndarray, row_num_1: int, row_num_2: int) -> np.ndarray:
M_copy = M.copy()
# exchange row 1 and row 2
temp = M_copy[row_num_1]
M_copy[row_num_1] = M_copy[row_num_2]
M_copy[row_num_2] = temp # I dont know why this method does not seem to work
return M_copy
any ideas as to why?
I tried implementing a function to swap the rows of a numpy array, but it does not seem to work
This is the code:
def SwapRows(M: np.ndarray, row_num_1: int, row_num_2: int) -> np.ndarray:
M_copy = M.copy()
# exchange row 1 and row 2
temp = M_copy[row_num_1]
M_copy[row_num_1] = M_copy[row_num_2]
M_copy[row_num_2] = temp # I dont know why this method does not seem to work
return M_copy
any ideas as to why?
Share Improve this question asked Mar 4 at 2:34 David NduonofitDavid Nduonofit 11 bronze badge 3 |1 Answer
Reset to default 0You need to add .copy()
to ensure no unintended references.
import numpy as np
def SwapRowsYours(M: np.ndarray, row_num_1: int, row_num_2: int) -> np.ndarray:
M_copy = M.copy()
# exchange row 1 and row 2.
temp = M_copy[row_num_1]
M_copy[row_num_1] = M_copy[row_num_2]
M_copy[row_num_2] = temp # I dont know why this method does not seem to work.
return M_copy
def SwapRowsWorking(M: np.ndarray, row_num_1: int, row_num_2: int) -> np.ndarray:
# Create a copy of the input array to avoid modifying the original array.
M_copy = M.copy()
# Swap the specified rows.
temp = M_copy[row_num_1].copy() # Use .copy() to ensure no unintended references.
M_copy[row_num_1] = M_copy[row_num_2]
M_copy[row_num_2] = temp
return M_copy
# Define a sample 2D NumPy array
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Swap rows 0 and 2
result = SwapRowsYours(M, 0, 2)
print("Original Array:")
print(M)
print("\nArray After Swapping Rows (Your Function):")
print(result)
# Swap rows 0 and 2
result = SwapRowsWorking(M, 0, 2)
print("\nArray After Swapping Rows (Working Function):")
print(result)
The output should be as follows:
Original Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Array After Swapping Rows (Your Function):
[[7 8 9]
[4 5 6]
[7 8 9]]
Array After Swapping Rows (Working Function):
[[7 8 9]
[4 5 6]
[1 2 3]]
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745063892a4609134.html
M[[row1,row2]] = M[[row2,row1]]
– Mark Setchell Commented Mar 4 at 3:08temp
is a whole row, and thus aview
. Check its value after the next line. – hpaulj Commented Mar 4 at 4:43