i need some help iterating through a loop of numpy functions. First I started to calculate all the values i was looking for and stored them in a dictionary.
calculations[keys[0]] = [np.mean(matrix, axis=0),np.mean(matrix, axis=1),np.mean(list)]
calculations[keys[1]] = [np.var(matrix, axis=0),np.var(matrix, axis=1),np.var(list)]
calculations[keys[2]] = [np.std(matrix, axis=0),np.std(matrix, axis=1),np.std(list)]
calculations[keys[3]] = [np.max(matrix, axis=0),np.max(matrix, axis=1),np.min(list)]
calculations[keys[4]] = [np.min(matrix, axis=0),np.min(matrix, axis=1),np.max(list)]
calculations[keys[5]] = [np.sum(matrix, axis=0),np.sum(matrix, axis=1),np.sum(list)]
Then I thought is there a better war to do this, via a loop. I tried some f string things, but it didn't work out.
list = [i for i in range(9)]
matrix = np.reshape(list,(3,3))
keys = ['mean','variance','standard deviation', 'max','min','sum']
operator = ['np.mean','np.var','np.std','np.max','np.min','np.sum']
calculations = {}
for i in range[len(keys)]:
calculations[keys[i]] = [f'{operater[0]}'(matrix, axis=0),f'{operater[0]}'(matrix, axis=1),f'{operater[0]}'(list)]
is there a way to go?
thanks in advance
CodePudding user response:
list
is a keyword and therefore should not be used as a variable, furthermore you need to use round ()
brackets for range
, not square []
ones.
In Python, functions are first class members, so you can just pass them around and save them in a list. Just do this:
import numpy as np
numbers = list(range(9))
matrix = np.reshape(numbers,(3,3))
keys = ['mean','variance','standard deviation', 'max','min','sum']
operator = [np.mean, np.var, np.std, np.max, np.min, np.sum]
calculations = {}
for i in range(len(keys)):
calculations[keys[i]] = [operator[i](matrix, axis=0),operator[i](matrix, axis=1),operator[i](numbers)]