在Python中,我如何创建一个numpy数组的任意形状填充全真或全假?
当前回答
赶紧跑了一遍,看看np之间是否有什么不同。Full和np。的版本。
回答:不
import timeit
n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"
print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")
结果:
np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s
重要的
关于np的帖子。空的(我不能评论,因为我的声誉太低了):
不要那样做。不要用np。null初始化一个全true数组
由于数组是空的,内存不会被写入,也不能保证你的值会是什么。
>>> print(np.empty((4,4), dtype=bool))
[[ True True True True]
[ True True True True]
[ True True True True]
[ True True False False]]
其他回答
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)
赶紧跑了一遍,看看np之间是否有什么不同。Full和np。的版本。
回答:不
import timeit
n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"
print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")
结果:
np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s
重要的
关于np的帖子。空的(我不能评论,因为我的声誉太低了):
不要那样做。不要用np。null初始化一个全true数组
由于数组是空的,内存不会被写入,也不能保证你的值会是什么。
>>> print(np.empty((4,4), dtype=bool))
[[ True True True True]
[ True True True True]
[ True True True True]
[ True True False False]]
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)
推荐文章
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 如何修剪空白的数组值在php
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "