Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - numpy.mean on varying row size

The numpy mean function works perfectly fine when the dimensions are the same.

a = np.array([[1, 2], [3, 4]])
a.mean(axis=1)
array([ 1.5,  3.5])

But if I do it with varrying row size it gives an error

a = np.array([[1, 2], [3, 4, 5]])
a.mean(axis=1)
IndexError: tuple index out of range

I cannot find anything on the documentation regarding this problem. I could calculate the mean myself but I would like to use the build in function for this, seeing that it should be possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an approach -

# Store length of each subarray
lens = np.array(map(len,a))

# Generate IDs based on the lengths
IDs = np.repeat(np.arange(len(lens)),lens)

# Use IDs to do bin-based summing of a elems and divide by subarray lengths
out = np.bincount(IDs,np.concatenate(a))/lens

Sample run -

In [34]: a   # Input array
Out[34]: array([[1, 2], [3, 4, 5]], dtype=object)

In [35]: lens = np.array(map(len,a))
    ...: IDs = np.repeat(np.arange(len(lens)),lens)
    ...: out = np.bincount(IDs,np.concatenate(a))/lens
    ...: 

In [36]: out  # Average output
Out[36]: array([ 1.5,  4. ])

Simpler alternative way using list comprehension -

In [38]: [np.mean(i) for i in a]
Out[38]: [1.5, 4.0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...