np.vectorize giving me IndexError: invalid index to scalar variable - python

trying out something simple and it's frustratingly not working:
def myfunc(a,b):
return a+b[0]
v = np.vectorize(myfunc, exclude=['b'])
a = np.array([1,2,3])
b = [0]
v(a,b)
This gives me "IndexError: invalid index to scalar variable."
Upon printing b, it appears that the b taken in by the function is always 0, instead of [0]. Can I specify which arguments should be vectorized and which should remain constant?

When you use excluded=['b'] the keyword parameter b is excluded.
Therefore, you must call v with keyword arguments, e.g. v(a=a, b=b) instead of v(a, b).
If you wish to call v with positional arguments with the second positional argument excluded, then use
v = np.vectorize(myfunc)
v.excluded.add(1)
For example,
import numpy as np
def myfunc(a, b):
return a+b[0]
a = np.array([1,2,3])
b = [0, 1]
v = np.vectorize(myfunc, excluded=['b'])
print(v(a=a, b=b))
# [1 2 3]
v = np.vectorize(myfunc)
v.excluded.add(1)
print(v(a, b))
# [1 2 3]

Well here is the answer:
v.excluded.add(1) works, though passing exclude=['b'] does not, for some reason.

Just add print to see what happens:
def myfunc(a, b):
print(a, b)
return a + b
v = np.vectorize(myfunc)
a = np.array([1,2,3])
b = np.array([0])
v(a, b)
Output:
1 0
1 0
2 0
3 0
The function is applied to all elements of the array. So it receives only scalar values. You cannot index a scalar.

Related

How to use one output of a function and store a second one=

So I have a function which outputs 2 values:
def example(a, b):
c = math.floor(a / b)
a = a%b
return (c, a)
I want to use this function this way:
print("text: ", c)
How can I use the function and print c, but store x for later?
Your function will return a tuple containing the two values. You can assign the result of calling your function to a variable.
Note,
that the parentheses are not required in your return statement.
you can replace math.floor(a / b) with a // b which will also do a floor division.
An example is shown below where the result of calling the function is unpacked into two variables, c and a.
def example(a, b):
c = a // b
a = a % b
return c, a
c, a = example(6, 3)
print("text:", c)
Alternatively, you can also store the result in a single variable that references your tuple as follows:
data = example(6, 3)
print("text:", data[0])
First, you need to call the function and assign its return values to some variables:
x, y = example(42, 5)
Then you can print the results:
print(x)
print(y)
You can even skip the variable assignment if you wish so
print("text:", example(a, b)[0])
but it's ugly

Program based on functions in Python

def add_sub(x,y):
d=x+y
e=x-y
return d,e
result=add_sub(7,6)
print(result)
The output for this function is (13,1), but i need output as mentioned below:
13
1
It needs to be like this:
def add_sub(x,y):
d=x+y
e=x-y
return d,e
result=add_sub(7,6)
for val in result:
print(val)
Since the result is returned on the tuple, tuple prints on that small braces.
Also, you can do this:
def add_sub(x,y):
d=x+y
e=x-y
return d,e
result=add_sub(7,6)
print("\n".join(map(str, result)))
When your function returns an iterable (a tuple in your case), and you know how many elements it will have, you can unpack it very easily:
def add_sub(x, y):
d = x + y
e = x - y
return d, e
result_add, result_sub = add_sub(7,6)
print(result_add)
# 13
print(result_sub)
# 1

Slice an array with a list of indices

Suppose a = array([1,2,3]) and b = array([4,5,6]). I want to slice a and b using a list and perform some operation on each part, then return the result to an array. For example i propose a dummy function that demonstrates the usage:
def dummy_function(i):
A = sum(a[:i])
B = sum(cumsum(b[i:]))
return A*B
For example, this function would return dummy_function(2) = 18, and dummy_function(1) = 16 but I would like to evaluate it using a list as its argument:
>>> dummy_function([2,1])
array([18,16])
Instead I get IndexError: invalid slice. I don't want to use a loop to iterate over the elements of [2,1] because I believe it can be done more effectively. How can I do what I want?
I don't know if I understood what you want correctly, but this worked for me:
import numpy as np
def func(i):
a = np.array([1,2,3])
b = np.array([4,5,6])
A = np.sum(a[:i])
B = np.cumsum(b[i:])
C = A*B
return C[0]
print(func(2))
The result is 18
If you want to give your 'func' a list as argument, then you probably should loop over the list elements..

Integrating equation using scipy

from scipy.integrate import quad
def integrand(a, b):
return a * x ** 2 + b
a = 2
b = 1
I = quad(integrand, 0, 1, args=(a,b))
I
This is my program. When I tried to run it, it was showing error :
integrand () takes 2 positional arguments but 3 were given ....
I didn't understand why it is asking for 3 arguments when there are only two variables, i.e. a and b.
Can anyone help me? Can anyone clarify my doubts?
Just replace
def integrand(a, b):
by
def integrand(x, a, b):
The problem is that in the function, you use a variable x but you do not pass the variable x as an argument to the function. 0 and 1 acts as the limits of the integral but since you are integrating w.r.t. x, you get this error.
Output
(1.6666666666666667, 1.8503717077085944e-14)
a*x**2+b This function you are using contain a variable x, in your case def integrand(a, b): does not contain a variable x which uses 0 to 1 limits of the integral you are using on I=quad(integrand,0,1,args=(a,b)).
So all you have to do is add x to your def;
def integrand(x, a, b):
return a * x ** 2 + b
a = 2
b = 1
I = quad(integrand,0,1,args=(a,b))
I

subscripting with 2 arguments in python

Assume I have a class X which has 2 attributes : i and j.
I want to have :
x = X((1,2,3),(2,3,4)) #this would set i to (1,2,3) and j to (2,3,4)
I now want subscripting to work in the following way :
a, b = x[1,2] #a should now be 2 and b should now be 3
At the moment I'm trying this :
def __getitem__(self, i, j):
return self.x[i] , self.y[j]
However this keeps giving me the error that getitem takes in exactly 3 arguments but 2 is given (when I try to print out x[1,2] for instance)
Comma is the tuple packing operator. x[1, 2] calls x.__getitem__((1, 2)).
def __getitem__(self, ij):
i, j = ij
return self.x[i], self.y[j]

Categories