How do I modify particular a row or column of a NumPy array?
如何修改NumPy阵列的特定行或列?
For example I have a NumPy array as follows:
例如,我有一个NumPy数组,如下所示:
P = array([[1, 2, 3],
[4, 5, 6]])
How do I change the elements of first row, [1, 2, 3]
, to [7, 8, 9]
so that the P
will become:
如何将第一行[1,2,3]的元素更改为[7,8,9],以便P变为:
P = array([[7, 8, 9],
[4, 5, 6]])
Similarly, how do I change first column values, [2, 5]
, to [7, 8]
?
同样,如何将第一列值[2,5]更改为[7,8]?
P = array([[1, 7, 3],
[4, 8, 6]])
2 个解决方案
#1
21
Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python.
可以使用Python中的方括号索引表示法选择或修改NumPy数组的行和列。
To select a row in a 2D array, use P[i]
. For example, P[0]
will return the first row of P
.
要选择2D阵列中的行,请使用P [i]。例如,P [0]将返回P的第一行。
To select a column, use P[:, i]
. The :
essentially means "select all rows". For example, P[:, 1]
will select all rows from the second column of P
.
要选择列,请使用P [:,i]。 :基本上是指“选择所有行”。例如,P [:,1]将选择P的第二列中的所有行。
If you want to change the values of a row or column of an array, you can assign it to a new list (or array) of values of the same length.
如果要更改数组的行或列的值,可以将其分配给具有相同长度的值的新列表(或数组)。
To change the values in the first row, write:
要更改第一行中的值,请写入:
>>> P[0] = [7, 8, 9]
>>> P
array([[7, 8, 9],
[4, 5, 6]])
To change the values in the second column, write:
要更改第二列中的值,请写入:
>>> P[:, 1] = [7, 8]
>>> P
array([[1, 7, 3],
[4, 8, 6]])
#2
1
In a similar way if you want to select only two last columns for example but all rows you can use:
以类似的方式,如果您只想选择两个最后一列,例如您可以使用的所有行:
print P[:,1:3]
#1
21
Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python.
可以使用Python中的方括号索引表示法选择或修改NumPy数组的行和列。
To select a row in a 2D array, use P[i]
. For example, P[0]
will return the first row of P
.
要选择2D阵列中的行,请使用P [i]。例如,P [0]将返回P的第一行。
To select a column, use P[:, i]
. The :
essentially means "select all rows". For example, P[:, 1]
will select all rows from the second column of P
.
要选择列,请使用P [:,i]。 :基本上是指“选择所有行”。例如,P [:,1]将选择P的第二列中的所有行。
If you want to change the values of a row or column of an array, you can assign it to a new list (or array) of values of the same length.
如果要更改数组的行或列的值,可以将其分配给具有相同长度的值的新列表(或数组)。
To change the values in the first row, write:
要更改第一行中的值,请写入:
>>> P[0] = [7, 8, 9]
>>> P
array([[7, 8, 9],
[4, 5, 6]])
To change the values in the second column, write:
要更改第二列中的值,请写入:
>>> P[:, 1] = [7, 8]
>>> P
array([[1, 7, 3],
[4, 8, 6]])
#2
1
In a similar way if you want to select only two last columns for example but all rows you can use:
以类似的方式,如果您只想选择两个最后一列,例如您可以使用的所有行:
print P[:,1:3]