NumPy 数组初始化(填充相同的值) [英] NumPy array initialization (fill with identical values)

查看:43
本文介绍了NumPy 数组初始化(填充相同的值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个长度为 n 的 NumPy 数组,其中每个元素都是 v.

还有什么比:

a = empty(n)对于范围(n)中的我:a[i] = v

我知道 zerosones 可以用于 v = 0, 1.我可以使用 v *ones(n),但它vNone 时不起作用,而且 会慢得多.

解决方案

NumPy 1.8 引入 np.full(),这是一种比empty()后接fill()更直接的创建数组的方法填充某个值:

<预><代码>>>>np.full((3, 5), 7)数组([[ 7., 7., 7., 7., 7.],[ 7., 7., 7., 7., 7.],[ 7., 7., 7., 7., 7.]])>>>np.full((3, 5), 7, dtype=int)数组([[7, 7, 7, 7, 7],[7, 7, 7, 7, 7],[7, 7, 7, 7, 7]])

这可以说是创建填充某些值的数组的方式,因为它明确描述了要实现的目标(并且原则上可以非常高效,因为它执行非常具体的任务).

I need to create a NumPy array of length n, each element of which is v.

Is there anything better than:

a = empty(n)
for i in range(n):
    a[i] = v

I know zeros and ones would work for v = 0, 1. I could use v * ones(n), but it won't work when v is None, and also would be much slower.

解决方案

NumPy 1.8 introduced np.full(), which is a more direct method than empty() followed by fill() for creating an array filled with a certain value:

>>> np.full((3, 5), 7)
array([[ 7.,  7.,  7.,  7.,  7.],
       [ 7.,  7.,  7.,  7.,  7.],
       [ 7.,  7.,  7.,  7.,  7.]])

>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).

这篇关于NumPy 数组初始化(填充相同的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆