Is there a function in Python that can do what Mapply do in R?
Basically I have a list of n inputs(each entry is a dataframe) for a function and corresponding lists(each list has the length of n) of parameters.
In each parameter lists, the position of each parameter corresponds to the respective position of input in the input list.
Now I wish to obtain the result in the exact order of the way I put my input, either in the form of a list with each element a dataframe(or matrix or whatever) or just one dataframe with all result appended. This is easily achievable in R using Mapply, but in python, I haven't got the luck to find any function that does the trick.
I haven't try this but one of the solution that i thought of is to pd.concat all lists(including input list and parameter lists) I got into one bulky list by column and apply the function to each row where I'll extract each element of the row to fill the function.
This might work but it would look quite stupid if there is actually one-line solution.
This is how I would deal with the problem in R:
result <- mapply(FUN = function(input, parameter1, parameter2) function_of_interest(input, parameter1, parameter2), input = input_list, parameter1 = parameter1_list, parameter2 = parameter2_list,... )
If I understand the question correctly, this example of mapply
in R:
A <- c(1, 2, 3)
B <- c(2, 3, 4)
my_multiplication <- function(x,y){return(x*y)}
C <- mapply(my_multiplication, A, B)
could be roughly equivalent to this Python code:
a = [1, 2, 3]
b = [2, 3, 4]
def my_multiplication(x, y):
return x * y
c = map(my_multiplication, a, b)
The c
is now a so called iterator. If I oversimplify, c
can be viewed as a function that returns:
a[0] * b[0]
on first call,
a[1] * b[1]
on second call,
a[2] * b[2]
on third (and last) call
i = 0
message = 'a[{}] * b[{}] = {} * {} = {}'
for result in c:
print(message.format(i, i ,a[i], b[i], result))
i += 1
prints
a[0] * b[0] = 1 * 2 = 2
a[1] * b[1] = 2 * 3 = 6
a[2] * b[2] = 3 * 4 = 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With