python - 在 NumPy 中计算数组的平均值

标签 python arrays list numpy

给定三个列表:

A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]

如何计算以下(列)的平均值?

  • [1, 4, 7] 的平均值
  • [2, 5, 8] 的平均值
  • [3, 6, 9] 的平均值

不是下面的(行),

  • [1, 2, 3] 的平均值
  • [4, 5, 6] 的平均值
  • [7, 8, 9] 的平均值

import numpy as np
A = np.array([1,2,3])
B = np.array([4,5,6])
C = np.array([7,8,9])

我该怎么办?

最佳答案

使用 numpy.ndarray.transpose :

>>> np.array([
...     [1,2,3],
...     [4,5,6],
...     [7,8,9]
... ]).transpose().mean(axis=1)
array([ 4.,  5.,  6.])

或使用 numpy.transpose :

>>> np.transpose([
...     [1,2,3],
...     [4,5,6],
...     [7,8,9]
... ]).mean(axis=1)
array([ 4.,  5.,  6.])

更新

正如 Dave Hirschfeld 评论的那样,axis=0 的平均值要好得多:

>>> np.array([
...     [1,2,3],
...     [4,5,6],
...     [7,8,9]
... ]).mean(axis=0)
array([ 4.,  5.,  6.])

关于python - 在 NumPy 中计算数组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886584/

相关文章:

python - 更改 numpy 数组的 dtype 会影​​响数据

c++ - std::vector 与 C++ 中的原始数组有多相似?

python - 在Python中生成时 "()"和 "[]"有什么区别?

python - 为数据框的选定列应用 select_dtypes

python - 从 appengine + python 发送推文

python - 在 python 终端中触发 Airflow DAG

c++ - 如何从该列表的元素中获取 std::list<T>::iterator?

python - Pandas groupby 检查一列是否相对另一列严格增加

javascript - 从 jQuery.post AJAX 调用返回数据?

JAVA - 使用列表重构多个 "instanceof"