最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to swap the rows of a numpy array - Stack Overflow

programmeradmin0浏览0评论

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 Try M[[row1,row2]] = M[[row2,row1]] – Mark Setchell Commented Mar 4 at 3:08
  • a[[0,3]]=a[[3,0]] swap 0 and 3 rows in matrix a – Alex Alex Commented Mar 4 at 3:08
  • temp is a whole row, and thus a view. Check its value after the next line. – hpaulj Commented Mar 4 at 4:43
Add a comment  | 

1 Answer 1

Reset to default 0

You 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]]
发布评论

评论列表(0)

  1. 暂无评论