由 fromfunction 错误创建的 NumPy [英] NumPy creation by fromfunction error

查看:65
本文介绍了由 fromfunction 错误创建的 NumPy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

n=3x=np.fromfunction(lambda i,j: (i==1)and(j==1), (n,n), dtype=int)

导致ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()"

有什么问题吗?

解决方案

文档具有误导性.该函数不会使用每个单元格的索引重复调用;它被调用一次,索引数组同时表示所有单元格的索引.直接返回这一函数调用的返回值:

<预><代码>>>>numpy.fromfunction(lambda *args: 1, (2, 2))1>>>numpy.fromfunction(lambda *args: args, (2, 2))(数组([[ 0., 0.],[ 1., 1.]]), 数组([[ 0., 1.],[ 0., 1.]]))

您需要更改函数才能以这种方式运行:

lambda i, j: (i==1) &(j==1)# ^ 元素按位和

Code:

n=3
x=np.fromfunction(lambda i,j: (i==1)and(j==1), (n,n), dtype=int)

leads to "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

What's the problem?

解决方案

The documentation is misleading. The function isn't called repeatedly with the indices of each individual cell; it's called once, with index arrays representing the indices of all the cells at once. The return value of this one function call is returned directly:

>>> numpy.fromfunction(lambda *args: 1, (2, 2))
1
>>> numpy.fromfunction(lambda *args: args, (2, 2))
(array([[ 0.,  0.],
       [ 1.,  1.]]), array([[ 0.,  1.],
       [ 0.,  1.]]))

You'll need to change your function to operate that way:

lambda i, j: (i==1) & (j==1)
#                   ^ elementwise bitwise and

这篇关于由 fromfunction 错误创建的 NumPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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