Change a specific row / column of a NumPy array

How to change a specific row or column of a NumPy array?

For example, I have a NumPy array as follows:

P = array([[1, 2, 3],
           [4, 5, 6]])

How do I change the elements of the first row, [1, 2, 3]on [7, 8, 9]to Pbecome:

P = array([[7, 8, 9],
           [4, 5, 6]])

In the same way, how can I change the values ​​of the second column,, [2, 5]to [7, 8]?

P = array([[1, 7, 3],
           [4, 8, 6]])
+12
source share
2 answers

Rows and columns of NumPy arrays can be selected or modified using the square bracket index sign in Python.

To select a row in a 2D array, use P[i]. For example, it P[0]will return the first line P.

, P[:, i]. : " ". , P[:, 1] P.

, ( ) .

, :

>>> P[0] = [7, 8, 9]
>>> P
array([[7, 8, 9],
       [4, 5, 6]])

, :

>>> P[:, 1] = [7, 8]
>>> P
array([[1, 7, 3],
       [4, 8, 6]])
+26

, , , , :

print P[:,1:3]
+1

All Articles