I am looking for an efficient way to apply a function to a numpy array. I know that I can for loop over the rows, and that I can use numpy.apply_along_axis for a function that returns something, but is there a way to do something like apply_along_axis without a return?
For example, if I have:
a_list_of_strings = [] A = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) def funct (row): global a_list_of_strings a_list_of_strings.append(some_other_complicated_function(row))
is there an analogous way to do numpy.apply_along_axis with A and this function?
Edit: The reason I want to do this is so that I can have a better implementation of the following code (which I didn't originally post because I thought it was hard to read.
def entropy (array):
"""calculates the entropy of a static array"""
values = []
for i in range(3,len(types)+3):
p_s = sum(array[:,0]==i)/array.shape[0]
values.append(p_s)
return(sum(list(map(helper_ent,values))))
def helper_ent (p):
return (-p*np.log2(p+eps))
def calc_entropies (array):
entropies = []
eap = entropies.append
for i in range(1,len(array)+1):
split1 = array[array[:,i]==1.]
split2 = array[array[:,i]==0.]
if split1.shape[0]>0 and split2.shape[0]>0:
E = split1.shape[0]/array.shape[0]*entropy(split1)+split2.shape[0]/array.shape[0]*entropy(split2)
eap(E)
else:
eap(1)
return(np.array(entropies))</pre>