Python 如何用numpy数组中的值替换一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28952946/
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 03:56:02  来源:igfitidea点击:

How to replace one column by a value in a numpy array?

pythonarraysnumpy

提问by Jika

I have an array like this

我有一个这样的数组

import numpy as np

a = np.zeros((2,2), dtype=np.int)

I want to replace the first column by the value 1. I did the following:

我想用 value 替换第一列1。我做了以下事情:

a[:][0] = [1, 1] # not working
a[:][0] = [[1], [1]] # not working

Contrariwise, when I replace the rows it worked!

相反,当我替换它工作的行时!

a[0][:] = [1, 1] # working

I have a big array, so I cannot replace value by value.

我有一个大数组,所以我不能按值替换值。

采纳答案by Alex Riley

You can replace the first column as follows:

您可以按如下方式替换第一列:

>>> a = np.zeros((2,2), dtype=np.int)
>>> a[:, 0] =  1
>>> a
array([[1, 0],
       [1, 0]])

Here a[:, 0]means "select all rows from column 0". The value 1is broadcast across this selected column, producing the desired array (it's not necessary to use a list [1, 1], although you can).

这里的a[:, 0]意思是“从第 0 列中选择所有行”。该值1在这个选定的列中广播,生成所需的数组([1, 1]虽然您可以使用 list ,但没有必要使用)。

Your syntax a[:][0]means "select all the rows from the array aand then select the first row". Similarly, a[0][:]means "select the first row of aand then select this entire row again". This is why you could replace the rows successfully, but not the columns - it's necessary to make a selection for axis 1, not just axis 0.

您的语法a[:][0]表示“从数组中选择所有行a,然后选择第一行”。同样,a[0][:]表示“选择第一行,a然后再次选择整行”。这就是为什么您可以成功替换行,但不能成功替换列 - 有必要为轴 1 进行选择,而不仅仅是轴 0。

回答by Kasramvd

Select the intended column using a proper indexing and just assign the value to it using =. Numpy will take care of the rest for you.

使用适当的索引选择预期的列,然后使用=. Numpy 会为你处理剩下的事情。

>>> a[::,0] = 1
>>> a
array([[1, 0],
       [1, 0]])

Read more about numpy indexing.

阅读有关numpy 索引的更多信息。

回答by Zhiya

You can do something like this:

你可以这样做:

import numpy as np

a = np.zeros((2,2), dtype=np.int)
a[:,0] = np.ones((1,2), dtype=np.int)

Please refer to Accessing np matrix columns

请参阅访问 np 矩阵列