如何制作一个与给定数组相同大小的新numpy数组,并用标量值填充它 [英] how to make a new numpy array same size as a given array and fill it with a scalar value
问题描述
我有一个带有一些随机数的numpy数组,如何创建一个具有相同大小的新数组并用单个值填充它?
I have a numpy array with some random numbers, how can I create a new array with the same size and fill it with a single value?
我有以下代码:
A=np.array([[2,2],
[2,2]])
B=np.copy(A)
B=B.fill(1)
我想要一个新数组B,其大小与A相同,但填充为1s.但是,它返回一个None
对象.使用np.full
时相同.
I want to have a new array B with the same size as A but filled with 1s. However, it returns a None
object. Same when using np.full
.
推荐答案
You can use np.full_like
:
B = np.full_like(A, 1)
这将创建一个具有与A
相同属性的数组,并将其填充为1
.
This will create an array with the same properties as A
and will fill it with 1
.
In case you want to fill it with 1
there is a also a convenience function: np.ones_like
B = np.ones_like(A)
您的示例不起作用,因为B.fill
不返回任何内容.它可以就地"运行.因此,您填充了B
,但是立即用fill
的None
返回值覆盖了变量B
.如果您这样使用它,它将起作用:
Your example does not work because B.fill
does not return anything. It works "in-place". So you fill your B
but you immediatly overwrite your variable B
with the None
return of fill
. It would work if you use it like this:
A=np.array([[2,2], [2,2]])
B=np.copy(A)
B.fill(1)
这篇关于如何制作一个与给定数组相同大小的新numpy数组,并用标量值填充它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!