python - numpy 中的数组操作

标签 python numpy

如何通过计算均值从原始数组(x)得到新数组(new)如下:

new = [[mean(1,3), mean(1,3), mean(1,3), mean(1,3), mean(1,3)],[mean(2,4),mean(2,4),mean(2,4),mean(2,4),mean(2,4)]]


import numpy as np

arr1 = np.array([[1,1,1,1,1],[2,2,2,2,2]])
arr2 = np.array([[3,3,3,3,3],[4,4,4,4,4]])
my_array = np.array([arr1,arr2])

for x in my_array:    
    new = np.mean(x,axis=1)
    print (new)

重要提示: arr1、arr2 和 my_array 并不是真正可用的输入,可用的只有 x。所以,真正要操作的数据是以x给出的for循环的形式,如上所示。

最佳答案

给定 my_array 如上定义

>>> my_array
array([[[1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]]])

您只需按如下方式在第一个轴上取平均值:

>>> my_array.mean(axis=0)
array([[ 2.,  2.,  2.,  2.,  2.],
       [ 3.,  3.,  3.,  3.,  3.]])

如果后续 x 必须迭代,您可以执行以下操作:

sums = 0
counter = 0
for x in my_array:
  sums += x
  counter += 1
new = sums / counter

或者,如果您可以存储数据:

data = []
for x in my_array:
  data.append(x)
new = np.dstack(data).mean(axis=2)

关于python - numpy 中的数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20517820/

相关文章:

python - 使用 OpenCV detectMultiScale 加载 Numpy 数组二进制图像

python - 如何使用属性简化这段代码?

python - selenium.common.exceptions.NoSuchElementException:消息:无法找到 element://pre/*[not(self::b)]

python - 如何有效地将形状为(w,h,3)的numpy图像转换为在第三轴上具有r,g,b,x,y的(w,h,5)?

python - 在Python中将数组转换为元组/列表的快速方法?

python - 停止迭代 : generator_output = next(output_generator)

python - 在Python3中逐一读取列表的元素

python - Django_tagging (v0.3/pre) : Configuration issue

python - 将对象列表与自定义键进行比较

python - Unicode解码错误: 'ascii' codec can't decode byte 0xe6 in position 1206: ordinal not in range(128)