Numpy vectorize() 正在展平整个数组 [英] Numpy vectorize() is flattening the whole array
问题描述
我的输入是一个 numpy 元组数组
My input is a numpy array of tuples
values = np.array([(4, 5, 2, 18), (4, 7, 3, 8)])
我的功能如下:
def outerFunc(values):
print(values)
def innerFunc(values):
print(values)
mean = np.mean(values)
result = 0
for i in range(len(values)):
result += math.pow(values[i] - mean, 2)
return result
if isinstance(values, np.ndarray):
return np.vectorize(innerFunc)(values)
else:
return innerFunc(values)
虽然我想对1维进行向量化,即在innerFunc内部执行一个元组,但我的输出如下:
Although I want to vectorize over 1 dimension, i.e., one tuple is executed inside the innerFunc, but my output is as follows:
[[ 4 5 2 18]
[ 4 7 3 8]]
4
...
这意味着 vectorize 函数在 2 维上进行矢量化,并且我收到以下错误:
Which means the vectorize function is vectorizing over 2 dimensions, and I am getting the following error:
for i in range(len(values)):
TypeError: object of type 'numpy.int64' has no len()
要进行哪些更改以使输出为:
What changes to make so that the output is:
[[ 4 5 2 18]
[ 4 7 3 8]]
[4 5 2 18]
...
类似的东西
谢谢.
编辑
当元组长度不同时,它可以正常工作,任何人都可以解释这一点,
It is working as accepted when the tuples are different length, can anyone explain this,
例如,我的输入是
np.array([(4, 5, 2, 18), (4, 7, 3,)])
和函数打印
[(4, 5, 2, 18) (4, 7, 3)]
(4, 5, 2, 18)
(4, 7, 3)
返回值为
[158.75 8.66666667]
因此,只有当所有元组长度相同时,函数才会将它们视为数字.
So, only when all the tuples are the same length, the function treats them as numbers.
谢谢.
推荐答案
In [1]: values = np.array([(4, 5, 2, 18), (4, 7, 3, 8)])
In [2]: values
Out[2]:
array([[ 4, 5, 2, 18],
[ 4, 7, 3, 8]])
In [3]: values.shape
Out[3]: (2, 4)
In [4]: x=np.array([(4, 5, 2, 18), (4, 7, 3,)])
In [5]: x
Out[5]: array([(4, 5, 2, 18), (4, 7, 3)], dtype=object)
In [6]: x.shape
Out[6]: (2,)
values
是一个二维数值数组.np.vectorize
将 8 个元素中的每一个传递给您的内部函数,一次一个.它不会按行迭代.
values
is a 2d numeric array. np.vectorize
passes each of the 8 elements, one at a time, to your inner function. It does not iterate by rows.
x
是一个具有 2 个元素(元组)的一维数组.vectorize
会将这些元组中的每一个传递给您的内部.
x
is a 1d array with 2 elements (tuples). vectorize
will pass each of those tuples to your inner.
不要在简单迭代可行的情况下使用 vectorize
- 它会更慢且更难正确使用.
Don't use vectorize
when a simple iteration would work - it's slower and harder to use right.
并在创建数组后查看数组,确保您了解形状和数据类型.不要做假设.
And look at your arrays after you create them, making sure you understand the shape and dtype. Don't make assumptions.
这篇关于Numpy vectorize() 正在展平整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!