简体   繁体   English

如何在numpy数组中同时允许浮点数和和数组

[英]How to allow both floats and and array in a numpy array

Using numpy and matplotlib it seems quite common that functions allow both a number (float or int) or a numpy array as argument like this: 使用numpy和matplotlib似乎很常见,函数允许将数字(浮点数或整数)或numpy数组作为参数,如下所示:

import numpy as np

print np.sin(0)
# 0

x = np.arange(0,4,0.1)
y = np.sin(x)

In this example I call np.sin once with an integer argument, and once with a numpy array x . 在此示例中,我使用整数参数调用一次np.sin,并且使用numpy数组x调用一次。 I now want to write a function that allows similar treatment, but I don't know how. 我现在想编写一个允许类似处理的函数,但是我不知道如何做。 For example: 例如:

def fun(foo, n):
    a = np.zeros(n)
    for i in range(n):
        a[i] = foo
    return a

would allow me to call fun like fun(1, 5) but not like fun(x, 5) . 将允许我将fun称为fun fun(1, 5)而不是fun(x, 5) My actual calculation is much more complicated, of course. 当然,我的实际计算要复杂得多。

How can I initialize a such that I can have both simple numbers or a whole array of numbers as elements? 如何初始化a这样的对象,使我既可以将简单数字也可以将整个数字数组作为元素?

Thanks a lot for your help! 非常感谢你的帮助!

You need a to inherit the dimensions of foo : 您需要a来继承foo的尺寸:

def fun(foo, n):
    a = np.zeros((n,) + np.shape(foo))
    for i in range(n):
        a[i] = foo
    return a

Builtin numpy functions often start with a 内置的numpy函数通常以

 def foo(a, ...):
     a = np.asarray(a)
     ...

That is, they transform the input argument(s) to array (no copy if it is already an array). 也就是说,他们将输入参数转换为数组(如果已经是数组,则不复制)。 The allows them to work with scalars and lists. 允许他们使用标量和列表。

Once the argument is an array it has a shape and can be broadcasted against other arguments. 一旦参数是一个数组,它就具有形状,并且可以与其他参数一起广播。

In your example, it's unclear what is supposed to happen when foo is an array 在您的示例中,尚不清楚foo是数组时应该发生什么

def fun(foo, n):
    a = np.zeros(n)
    for i in range(n):
        a[i] = foo
    return a

a is initialized as a dtype float array. a初始化为dtype浮点数组。 That means a[i]=foo works only if foo is a single element number (scalar, possibly a single element array). 这意味着只有在foo是单个元素编号(标量,可能是单个元素数组)的情况下, a[i]=foo才有效。 If foo is an array with more than one value you probably get an error about attempting to set an element with a sequence. 如果foo是一个具有多个值的数组,则可能会收到有关尝试使用序列设置元素的错误。

a[i] is short for a[i,...] . a[i]a[i,...]缩写。 That is it indexes on the 1st dimension. 那就是它在第一维上的索引。 So if a was initialed correctly it could accept arrays as inputs (subject to broadcasting rules). 因此,如果a正确初始化,则可以接受数组作为输入(取决于广播规则)。

If a was initialed as np.zeros(n, dtype=object) , then a[i]=foo will work with anything, since it a just contains pointers to Python objects. 如果a草签作为np.zeros(n, dtype=object) ,则a[i]=foo将与任何工作,因为它a只包含指针Python对象。

np.frompyfunc is a way of generating an array from a function. np.frompyfunc是一种从函数生成数组的方法。 But it returns an array of dtype=object. 但是它返回一个dtype = object的数组。 np.vectorize uses that but gives you more control over the output type. np.vectorize使用它,但是可以让您更好地控制输出类型。 But both work with scalars. 但是两者都可以使用标量。 An array, if given as argument, is passed element by element to the function. 如果将数组作为参数给出,则将其逐个元素传递给函数。

You can use type identification : 您可以使用类型识别:

import numpy as np

def double(a):
    if type(a)==int:
        return 2*a
    elif type(a)==float:
        return 2.0*a
    elif type(a)==list:
        return [double(x) for x in a]
    elif type(a)==np.ndarray:
        return 2*a
    else:
        print "bad type"

print double(7)
print double(7.2)
print double([2,9,7])
print double(np.array([[9,8],[2,3]]))

result : 结果:

>14
>14.4
>[4, 18, 14]
>[[18 16]
 [ 4  6]]

with eventually a recursive treatement as I did on list 最终像我在清单上所做的那样进行递归处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM