I am trying to answer the questions below but I don't understand the error code when I run it (Required argument 'object' (pos 1) not found). Any help will be appreciated.
Write a python function that takes in two arrays and returns:
a) the mean of the first array
def first_mean(a,b):
a = np.array()
b = np.array()
return np.mean(a)
first_mean([2,3,4],[4,5,6])
b) the mean of the second array
def second_mean(a,b):
a = np.array()
b = np.array()
return np.mean(b)
second_mean([2,3,4],[4,5,6])
c) the Mann-Whitney U-statistic and associated p-value of the two arrays?
def mantest(a,b):
a = np.array()
b = np.array()
return scipy.stats.mannwhitneyu(a,b)
mantest([2,3,4],[4,5,6])
You are creating new, empty arrays in your functions for no reason. You are also giving them the same name as your input parameters, thus discarding your original input arrays.
What you are doing boils down to
>>> np.mean(np.array())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Required argument 'object' (pos 1) not found
All you need to do is delete the useless lines
a = np.array()
b = np.array()
from your functions.
Demo:
>>> def first_mean_nobody_knows_why_this_has_two_arguments(a, b):
... return np.mean(a)
...
>>> a = np.array([1,2,3])
>>> b = np.array([4,5,6])
>>> first_mean_nobody_knows_why_this_has_two_arguments(a, b)
2.0
Related
Below code I have.
from sympy import *
x = symbols('x')
expr = sin(x)
# Use sympy.lambdify() method
f = lambdify(x, expr, "math")
If print(f) its giving '<function _lambdifygenerated at 0x100d643a0>', is there any way to get back the expression(sin(x)) from f?
help(f) displays:
Help on function _lambdifygenerated:
_lambdifygenerated(x)
Created with lambdify. Signature:
func(x)
Expression:
sin(x)
Source code:
def _lambdifygenerated(x):
return sin(x)
f.__doc__ is the same string.
Since we specified 'math', scalars work, but not arrays:
In [12]: f(1.23)
Out[12]: 0.9424888019316975
In [13]: f(np.arange(3))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [13], in <module>
----> 1 f(np.arange(3))
File <lambdifygenerated-2>:2, in _lambdifygenerated(x)
1 def _lambdifygenerated(x):
----> 2 return sin(x)
TypeError: only size-1 arrays can be converted to Python scalars
I have gone into the source code of Sympy and found this line where the content of the lambdified function is defined in the variable funcstr:
https://github.com/sympy/sympy/blob/88b9cba9d7e633ec769baf1fc5267acfd7f54788/sympy/utilities/lambdify.py#L863
# Create the function definition code and execute it
funcname = '_lambdifygenerated'
if _module_present('tensorflow', namespaces):
funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter
else:
funcprinter = _EvaluatorPrinter(printer, dummify)
if cse == True:
from sympy.simplify.cse_main import cse as _cse
cses, _expr = _cse(expr, list=False)
elif callable(cse):
cses, _expr = cse(expr)
else:
cses, _expr = (), expr
funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses)
Currently Sympy does not return funcstr, but I modified it in my local installation so that it does, and it seems to be what you are after.
import sympy as sy
x = sy.symbols('x')
expr = sy.sin(x)
# Use sympy.lambdify() method
f, funcstr = sy.lambdify(x, expr, "math")
funcstr.split(":")[-1].split("return")[-1].strip()
>>> 'sin(x)'
The way I got the content out is a bit dodgy, and not necessarily robust, but I hope it gives you a starting point to work with.
Beware that if you used the argument cse, this extraction will not be accurate, since it will miss out on the previous simplifications.
I a function described as follows (very simplified version):
def my_func(*args):
c = other_func(args)
return c
And other_func is defined as:
def other_func(a, b):
c = a + b
return c
I have also two numpy arrays:
a = [[1.] [2.]]
b = [[2.] [5.]]
I want to pass a and b to my_func and retrieve them exactly as I passed them:
The result I want is :
c = my_func(a, b)
With :
c = [[3.] [7.]]
But when I call my_func like above, I get this error:
TypeError: other_func missing 1 required positional argument: 'b'
I think the problem is that my_func is not able to unpack the data.
I looked at an almost similar topic (link below) but It doesn't help me enough to fix my problem. Also, I don't want to use a Loop, it will not be practical for my work.
Link : How to split list and pass them as separate parameter?
Can anyone help me solve this?
Thank you in advance.
Change the line
c = other_func(args)
to
c = other_func(*args)
Given these 2 (2,1) arrays, a+b produces what you want:
In [776]: a = np.array([[1.], [2.]])
...: b = np.array([[2.], [5.]])
In [777]: a+b
Out[777]:
array([[3.],
[7.]])
In [778]: def my_func(a,b):
...: return a+b
...:
In [779]: my_func(a,b)
Out[779]:
array([[3.],
[7.]])
There is a certain ambiguity, since a matrix formed from them is symmetric
In [780]: np.concatenate((a,b), axis=1)
Out[780]:
array([[1., 2.],
[2., 5.]])
Adding rows or columns both produce the [3,7] values.
Overall your question is poorly specified
You want to iterate over the args list and unpack and input each array separately into other_func like this:
results = []
for arg in args:
results.append(other_func(*arg))
I am pretty much copying from the example given in online docs, but using filter() in windows-based Python 3 is perplexing me. What is wrong here:
a=[1,2,3,4]
b=[1,0,1,0]
f=filter(b,a)
for fs in f : print(fs)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
f=list(filter(b,a))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Online docs say to throw list() in, but that clearly helps not.
First argument of filter must be a function or lambda. You passed b which is a list.
Filter's documentation clearly states that it takes a function and an iterable as input. Perhaps if you want to check if a value is in both a and b, you could do something like:
f = filter(lambda x: x in b, a)
and then loop over f.
You are misunderstanding how filter works, filter needs a function that returns True for each item that you want to keep.
I'm assuming b describes the things in a you want to select, then you meant something like::
f = filter(lambda x: x[1], zip(a, b))
for fs, _ in f: ...
You can also replace filter with a list comprehension:
f = [x for x, y in zip(a, b) if y]
for fs in f: ...
But there is a function in itertools that does exactly this:
import itertools as it
f = it.compress(a, b)
for fs in f: ...
Basically filter takes a function and an iterable value to filter in
a = [1,2,3,4]
b = [1,0,1,0]
f = filter(lambda val: val not in b, a)
for fs in f: print(fs)
output:
2
3
4
Confusion occurs when we call filter with None
list(filter(None, [0,1,2]))
# This returns [1,2] Which is a special case
# and it is not equal to:
list(filter(1, [0,1,2])) #invalid
The reason being When we pass filter condition as None filter function checks each value in the list and sees if they qualify the if value condition.
Which roughly translates to this.
[value for value in [0,1,2] if value]
Is there a way to disable silent conversions in numpy?
import numpy as np
a = np.empty(10, int)
a[2] = 4 # OK
a[3] = 4.9 # Will silently convert to 4, but I would prefer a TypeError
a[4] = 4j # TypeError: can't convert complex to long
Can numpy.ndarray objects be configured to return a TypeError when assigning any value which is not isinstance() of the ndarray type?
If not, would the best alternative be to subclass numpy.ndarray (and override __setattr__ or __setitem__)?
Unfortunately numpy doesn't offer this feature in array creation, you can set if casting is allowed only when you are converting an array (check the documentation for numpy.ndarray.astype).
You could use that feature, or subclass numpy.ndarray, but also consider using the array module offered by python itself to create a typed array:
from array import array
a = array('i', [0] * 10)
a[2] = 4 # OK
a[3] = 4.9 # TypeError: integer argument expected, got float
Just an idea.
#Python 2.7.3
>>> def test(value):
... if '.' in str(value):
... return str(value)
... else:
... return value
...
>>> a[3]=test(4.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for long() with base 10: '4.0'
So, what im trying to do is get certain numbers from certain positions in a array of a given > range and put them into an equation
yy = arange(4)
xx = arange(5)
Area = ((xx[2] - xx[1])(yy[2] + yy[1])) / 2
I try to run it and I get this..
----> ((xx[2] - xx[1])(yy[2] + yy[1])) / 2
TypeError: 'numpy.int64' object is not callable
I get error.. how can I use certain numbers in an array and put them into an equation?
Python does not follow the same rules as written math. You must explicitly indicate multiplication.
Bad:
(a)(b)
(unless a is a function)
Good:
(a) * (b)
This error also occurs when your function has the same name as your return value
def samename(a, b):
samename = a*b
return samename
This might be a super rookie mistake, I am curious how often this answer will be helpful.
You are missing * when multiplying, try:
import numpy as np
yy = np.arange(4)
xx = np.arange(5)
Area = ((xx[2] - xx[1])*(yy[2] + yy[1])) / 2
This could happen because you have overwritten the name of the function that you attempt to call.
For example:
def x():
print("hello world")
...
x = 10.5
...
x()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
2 print("hello world")
3 x = 10.5
----> 4 x()
TypeError: 'float' object is not callable