在Python中,我如何创建一个numpy数组的任意形状填充全真或全假?
当前回答
答案是:
numpy.full((2, 2), True)
解释:
Numpy很容易创建全1或全0的数组:
例如numpy。Ones((2,2))或numpy。0 ((2, 2))
由于True和False在Python中分别表示为1和0,我们只需要使用可选的dtype参数指定该数组应为布尔值,就完成了:
numpy.ones((2, 2), dtype=bool)
返回:
array([[ True, True],
[ True, True]], dtype=bool)
更新日期:2013年10月30日
从numpy版本1.8开始,我们可以使用full来实现同样的结果,而且语法更清楚地显示了我们的意图(正如fmonegaglia指出的那样):
numpy.full((2, 2), True, dtype=bool)
更新:2017年1月16日
因为至少在numpy 1.12版本中,完全自动转换为第二个形参的dtype,所以我们可以这样写:
numpy.full((2, 2), True)
其他回答
Michael Currie回答的基准
import perfplot
bench_x = perfplot.bench(
n_range= range(1, 200),
setup = lambda n: (n, n),
kernels= [
lambda shape: np.ones(shape, dtype= bool),
lambda shape: np.full(shape, True)
],
labels = ['ones', 'full']
)
bench_x.show()
答案是:
numpy.full((2, 2), True)
解释:
Numpy很容易创建全1或全0的数组:
例如numpy。Ones((2,2))或numpy。0 ((2, 2))
由于True和False在Python中分别表示为1和0,我们只需要使用可选的dtype参数指定该数组应为布尔值,就完成了:
numpy.ones((2, 2), dtype=bool)
返回:
array([[ True, True],
[ True, True]], dtype=bool)
更新日期:2013年10月30日
从numpy版本1.8开始,我们可以使用full来实现同样的结果,而且语法更清楚地显示了我们的意图(正如fmonegaglia指出的那样):
numpy.full((2, 2), True, dtype=bool)
更新:2017年1月16日
因为至少在numpy 1.12版本中,完全自动转换为第二个形参的dtype,所以我们可以这样写:
numpy.full((2, 2), True)
numpy.full((2,2), True, dtype=bool)
>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
numpy。full(大小,标量值,类型)。还有其他参数可以传递,有关文档请查看https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html
Ones和zero分别创建充满1和0的数组,它们接受一个可选的dtype形参:
>>> numpy.ones((2, 2), dtype=bool)
array([[ True, True],
[ True, True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
[False, False]], dtype=bool)