numpy.mean on varying row size

自古美人都是妖i 提交于 2019-11-28 08:51:59

问题


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.


回答1:


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]


来源:https://stackoverflow.com/questions/40318013/numpy-mean-on-varying-row-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!