Answer the question
In order to leave comments, you need to log in
How to apply a function to a numpy array?
There is an array of 10000 by 5, in each line the first four elements are the coefficients for the function, and the fifth is 0. Is it possible, and if so, how, so that in each line the fifth element would be filled with the result of using the corresponding elements (the first four, on the same line) for a function without using for (I did it with it, example below). Below are examples of my attempts and auxiliary code.
Creating an array (Array contains zero 5 elements):
import numpy as np
list = []
for a in range(0, 10):
for b in range(0, 10):
for c in range(0, 10):
for d in range(0, 10):
list.append([a, b, c, d])
array = np.zeros((10000, 5))
for i in range(0, 10000):
for a in range(0, 4):
array[i, a] = list[i][a] * 0.001
def task(coef):
ad = float(coef[0] + coef[1] * coef[2] - coef[3])
if coef[0] != 0:
ad = ad/coef[0]
else:
ad = ad/100
return ad
for i in range(0, 10000):
array[i, 4] = task(array[i, 0:4])
Answer the question
In order to leave comments, you need to log in
via a list comprehension
on the input array - a list of lists of 4 elements. A list element of 4 elements is passed to task(), by elements of which it counts this value and writes it as the fifth value into a new element, which adds it to a new array
array_out=[ [i[0],i[1],i[2],i[3],task(i)] for i in array]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question