Python 修改 NumPy 数组的特定行/列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26975769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:14:26  来源:igfitidea点击:

Modify a particular row/column of a NumPy array

pythonarraysnumpy

提问by learner

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 Pwill become:

如何将第一行的元素 , 更改为[1, 2, 3][7, 8, 9]以便P将变为:

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

Similarly, how do I change second column values, [2, 5], to [7, 8]?

同样,如何将第二列值 , 更改[2, 5][7, 8]

P = array([[1, 7, 3],
           [4, 8, 6]])

回答by Alex Riley

Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python.

可以使用 Python 中的方括号索引符号选择或修改 NumPy 数组的行和列。

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

要选择二维数组中的一行,请使用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]])

回答by Armin Alibasic

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]

回答by Amirreza SV

If you have lots of elements in a column:

如果一列中有很多元素:

import numpy as np
np_mat = np.array([[1, 2, 2],
                   [3, 4, 5],
                   [5, 6, 5]])
np_mat[:,2] = np_mat[:,2] * 3
print(np_mat)

It is making a multiplied by 3 change in third column:

它在第三列中进行了乘以 3 的更改:

    [[ 1  2  6]
     [ 3  4 15]
     [ 5  6 15]]