迭代和Python中的多维数组选择特定阵列 [英] Iterating and selecting a specific array from a multidimensional array in Python

查看:440
本文介绍了迭代和Python中的多维数组选择特定阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象我有这样的事情:

 import numpy as np
 arra = np.arange(16).reshape(2, 2, 4)  

这使得

 array([[[0, 1, 2, 3],  
      [4, 5, 6, 7]],  
      [[8, 9, 10, 11],  
      [12, 13, 14, 15]]])     

和我想要沿着特定的子阵列上运行(在这种情况下,我想沿着每个'矩阵'的每个列运行)的循环,总结的结果(即,选择0和4,总结他们(4),在选择1和5以及对它们求和(6),...,选择3和7和对它们求和(10),选择8和12以及对它们求和(20),...,选择11和15和他们总结(26))。

and I want to make a loop that runs along specific subarrays (in this case, I want to run along each 'column' of each 'matrix') and sum the result (that is, selecting 0 and 4 and summing them (4), selecting 1 and 5 and summing them (6), ..., selecting 3 and 7 and summing them (10), selecting 8 and 12 and summing them (20), ..., selecting 11 and 15 and summing them (26)).

我曾想过这样做的显然是天然的:

I had thought doing that with the apparently natural:

 for i in arra[i, j, k]:  
     for j in arra[i, j, k]:  
         for k in arra[i, j, k]:  
             sum...  

问题是Python的肯定不允许做什么,我想用这种方式。如果它是一个二维数组,它会更容易些,因为我知道迭代器首先通过行运行,这样你就可以转沿列运行,但对于多维(3D在这种情况下)阵列(N,M,P)与N,M,P >> 1,我不知道如何可以做到。

The problem is that Python certainly doesn't allow to do what I want in this way. If it were a 2D array it would be easier as I know that the iterator first runs through the rows, so you can transpose to run along the columns, but for a multidimensional (3D in this case) array (N, M, P) with N, M, P >> 1, I was wondering how it could be done.

编辑:这个问题有一个在这里延续:<一href=\"http://stackoverflow.com/questions/35775040/choosing-and-iterating-specific-sub-arrays-in-multidimensional-arrays-in-python\">Choosing并遍历在Python中多维数组的特定子阵列

This question has a continuation here: Choosing and iterating specific sub-arrays in multidimensional arrays in Python

推荐答案

您可以使用的 地图 来完成这件事:

You can use map to get this done:

import numpy as np
arra = np.arange(16).reshape(2, 2, 4)  

然后命令:

map(sum, arra)

为您提供所需的输出:

gives you the desired output:

[array([ 4,  6,  8, 10]), array([20, 22, 24, 26])]

另外,您还可以使用名单COM prehension

res = [sum(ai) for ai in arra]

然后 RES 是这样的:

[array([ 4,  6,  8, 10]), array([20, 22, 24, 26])]

编辑:

如果您要添加相同的行 - 因为你在这个答案下面的评论中提到的 - 你可以这样做(使用的 拉链 ):

If you want to add identical rows - as you mentioned in the comments below this answer - you can do (using zip):

map(sum, zip(*arra))

它给你所需要的输出:

which gives you the desired output:

[array([ 8, 10, 12, 14]), array([16, 18, 20, 22])]

有关完整起见也列表玉米prehension:

For the sake of completeness also the list comprehension:

[sum(ai) for ai in zip(*arra)]

它给你同样的输出。

which gives you the same output.

这篇关于迭代和Python中的多维数组选择特定阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆