numpy.mean不同的行大小

时间:2016-10-29 10:08:38

标签: python numpy mean

当尺寸相同时,numpy mean函数完全正常。

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

但是,如果我使用变量行大小来执行此操作,则会出现错误

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

我在文档中找不到有关此问题的任何内容。我可以自己计算平均值但是我想在这里使用build in函数,看它应该是可能的。

1 个答案:

答案 0 :(得分:1)

这是一种方法 -

grvCustomer.FirstDisplayedScrollingRowIndex = IndexRow;

示例运行 -

# 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

使用列表理解的更简单的替代方法 -

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. ])
相关问题