1

This is my current code:

import numpy as np

vec0 = [1, 2, 3]
vec1 = [2, 3, 4]
vec2 = [3, 4, 5]
vec3 = [4, 5, 6]

for k in range(0, 4):
    globals()['mean%s' % k] = np.mean('vec'+str(k))

I'm getting this error:

TypeError: cannot perform reduce with flexible type


I want to this result.

mean0 = np.mean(vec0)
mean1 = np.mean(vec1)
mean2 = np.mean(vec2)
mean3 = np.mean(vec3)
2
  • 1) You don't want to be creating dynamically named variables and 2) if you use numpy properly, you can make that a single 2D array and take the mean over the row axis... Commented Oct 21, 2017 at 17:57
  • This is actually an anti-pattern, Usually it is bad design to call variables by name. Commented Oct 21, 2017 at 17:58

3 Answers 3

1

It is an anti-pattern to call variables by name. In case you need to perform a task on multiple objects, you can construct a collection (a tuple, a list, etc.) of these objects. For instance:

all_vecs = [vec0, vec1, vec2, vec3]

Furthermore you can now easily process the averages in bulk with numpy by specifying an axis parameter:

all_means = np.mean(all_vecs,axis=1)

then:

>>> all_means
array([ 2.,  3.,  4.,  5.])
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this:

vecs = [vec0, vec1, vec2, vec3]

and then :

globals()['mean%s' % k] = np.mean(vecs[k])

Although, you should avoid this approach and maintain a 2D Array instead, which will be easier for computing means using the row-axis.

What I mean is, instead of this:

vec0 = [1, 2, 3]
vec1 = [2, 3, 4]
vec2 = [3, 4, 5]
vec3 = [4, 5, 6]

you can have something like this :

vecs = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])

and then you can simply calculate the means like this:

meansArray = vecs.mean(axis=1)

which will have your mean0, mean1, mean2, mean3 at the respective indices.

Comments

1

You can do it by changing:

globals()['mean%s' % k] = np.mean('vec'+str(k))

to

globals()['mean%s' % k] = np.mean(globals()['vec%s' % k])

But I highly recommend using a vector instead:

all_vec = [vec0, vec1, vec2, vec3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.