【问题标题】:numpy.mean on varying row sizenumpy.mean 在不同的行大小上
【发布时间】:2017-03-12 02:37:54
【问题描述】:

当维度相同时,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

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

【问题讨论】:

  • 第二种情况是一维对象数组,列表。使它成为一个数组并没有多大作用。您或 numpy 仍然必须将其视为列表列表。

标签: python numpy mean


【解决方案1】:

这是一种方法 -

# 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. ])

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

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

【讨论】:

  • 这正是我们所需要的,但这真的是解决这个问题的最简单方法吗?
  • @NicolaiF 为此,我们可以使用编辑中添加的`列表理解`。
  • 感谢您的全面回答!
猜你喜欢
  • 2020-08-02
  • 1970-01-01
  • 2015-10-29
  • 2021-04-18
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多