I have been trying to create a function that loops over my data, standardizes the values, and finally, puts the new values into a list. Here is what I am trying:
def standardize( num_list):
s = np.std(num_list)
Xmean = np.mean(num_list)
for i in num_list:
Xstd = (i - Xmean)/s
return Xstd
The function I have created only returns a single value. Next I tried this:
def standardize( num_list):
s = np.std(num_list)
Xmean = np.mean(num_list)
for i in num_list:
Xstd = (i - Xmean)/s
list = print(Xstd)
return
This is printing all the values I want, however, it is not placing them in a list. What am I missing to create a list?
Append them to a list:
def standardize(num_list):
s = np.std(num_list)
Xmean = np.mean(num_list)
lst = []
for i in num_list:
Xstd = (i - Xmean)/s
lst.append(Xstd)
return lst
This could also be done with a list comprehension (although more complicated computations cannot be):
def standardize(num_list):
s = np.std(num_list)
Xmean = np.mean(num_list)
return [(i - Xmean) / s for i in num_list]
In your example
def standardize( num_list):
s = np.std(num_list)
Xmean = np.mean(num_list)
for i in num_list:
Xstd = (i - Xmean)/s
return Xstd
The loop assigns the variable each time and then when it goes to return it is giving you the last value it assigned.
Try define a list, adding to it, then returning the list like
def standardize( num_list):
s = np.std(num_list)
Xmean = np.mean(num_list)
return_list = []
for i in num_list:
Xstd = (i - Xmean)/s
return_list.append(Xstd)
return return_list
Not tested
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.