1
stdev = 3   
value_1 = array   
value_2 = array   
value_3 = array

for h in range(1,4):  
    name = ('value' + str(h))  
    globals()['new_name_'+ str(h)] = np.mean(name) * stdev  

It should give something like this:

new_name_1 = #result1   
new_name_2 = #result2   
new_name_3 = #result3 

However, np.mean() does not work with str.
I tried to use unicode and other things.
I have to get the results(new name) by using globals(). Does somebody know how to do it?

martineau
  • 119,623
  • 25
  • 170
  • 301
Daniel_c
  • 11
  • 1
  • 5
    This is a really bad approach. You shouldn't be messing with `globals()` to make a variable number of variables. You want a dictionary of arrays instead. "I have to get the results(new name) by using globals()" you almost certainly _don't_ need to do that. Other than that, what is the mean of a string? `np.mean(name)` is just passing the string of the variable name to `mean()`, not the array stored against it. Also, `name = ('value' + str(h))` is incapable of making the actual variable name because it lacks the underscore, but that's a side issue – roganjosh Jan 03 '20 at 13:24
  • The fact that the rest of the code can't reference the variable that's created by the name given to it is one of the primary reasons it's not the best practice. Putting it in an existing container such as a dictionary would allow it to referenced by an associated id of your choosing, like a unique string or number. – martineau Jan 03 '20 at 13:51

1 Answers1

0

you can use a list to keep your arrays:

stdev = 3   
my_list = [array_1, array_2, array_3]
new_vars = []

for arr in my_list:  
    new_vars.append(np.mean(arr) * stdev)

also, you can keep your variables using a dict:

stdev = 3   
my_dict = {
    'value_1': array_1, 
    'value_2': array_2,
    'value_3': array_3}

new_vars = {}

for var_name, arr in my_dict.items():  
    new_vars[f'new_{var_name}'] = np.mean(arr) * stdev
kederrac
  • 16,819
  • 6
  • 32
  • 55
  • Instead of a list, you should use a dictionary so that they can still refer to objects by name (which is what they want to do) – roganjosh Jan 03 '20 at 13:30
  • if you look at there names, the only distinguishing thing is their index, so using a list will be more simple, but yes the OP can also use a dict – kederrac Jan 03 '20 at 13:37