numpy的数组初始化(具有相同值填写) [英] numpy array initialization (fill with identical values)

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

问题描述

我需要创建长度的numpy的阵列 N ,每个元素都是其中 v

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

有什么比更好的:

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

我知道那些将为V = 0的工作,1。我可以用 v *的人(N),但它不会工作,当 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引入了<一个href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html\"><$c$c>np.full(),这是比一个更直接的方法空()然后按填写()创建充满一定值的数组

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天全站免登陆