简体   繁体   English

使用元组列表作为二维 Numpy 数组中列乘积的索引

[英]Using a list of tuples as indices for the product of columns in a 2D Numpy array

I have a 2D numpy array A and a list of tuples tup that look like:我有一个2D numpy的阵列A和元组的列表, tup ,看起来像:

A = np.array(range(1,11)).reshape(-3,2)
A
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])

tup = [(0,),
 (1,),
 (0, 1),
 (0, 0),
 (1, 1),
 (0, 1, 1),
 (1, 1, 1),
 (0, 0, 0),
 (0, 0, 1)]

I'm looking to create a new np.array as result whose columns are products of the columns of A: the indices of the columns to be used in the products are given by the values in the tuples.我希望创建一个新的np.array作为result其列是 A 列的乘积:乘积中要使用的列的索引由元组中的值给出。 For example, the above should yield:例如,上面应该产生:

[[1,3,5,7,9],
[2,4,6,8,10],
[2,12,30,56,90],
[1,9,25,49,81],
[4,16,36,64,100],
[4,48,180,448,900],
...]]

Where the rows above correspond to:上面的行对应于:

[A[0],
A[1],
A[0]*A[1],
A[0]*A[0],
A[1]*A[1],
A[0]*A[1]*A[1],
A[1]*A[1]*A[1],
...]

The tuples can be of any length >= 1. So far I've tried iterating through each index of tup and looping through the number of entries of each tuple, but I'm having difficulty writing out the product given the number of terms per product varies for different iterations.元组可以是任何长度> = 1。到目前为止,我已经尝试过的每个索引迭代tup ,并通过每个元组的条目数循环,但我有给定条件的每数量难度写出来的产品产品因不同的迭代而异。 Any help or direction is much appreciated!非常感谢任何帮助或指导! Slight preference towards base Python and/or Numpy solutions.对基本 Python 和/或 Numpy 解决方案略有偏好。

In [135]: A = np.array(range(1,11)).reshape(-3,2)
In [136]: tup = [(0,),
     ...:  (1,),
     ...:  (0, 1),
     ...:  (0, 0),
     ...:  (1, 1),
     ...:  (0, 1, 1),
     ...:  (1, 1, 1),
     ...:  (0, 0, 0),
     ...:  (0, 0, 1)]

Let's try some indexing让我们尝试一些索引

In [137]: A[0,tup[0]]
Out[137]: array([1])
In [138]: A[0,tup[1]]
Out[138]: array([2])
In [141]: A[0,tup[2]]
Out[141]: array([1, 2])

or for all rows of A :或对于A所有行:

In [142]: A[:,tup[2]]
Out[142]: 
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])

and the desired product:和所需的产品:

In [143]: np.prod(A[:,tup[2]],axis=1)
Out[143]: array([ 2, 12, 30, 56, 90])

Now do this for a elements of tup .现在对tup的元素执行此操作。

[np.prod(A[:,k],axis=1) for k in tup]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM