python在列之间提供所有可能的产品

python在列之间提供所有可能的产品,python,numpy,itertools,Python,Numpy,Itertools,我有一个numpy矩阵X,我想把2列之间所有可能的乘积作为新变量添加到这个矩阵中 So if X=(x1,x2,x3) I want X=(x1,x2,x3,x1x2,x2x3,x1x3) 有没有一种优雅的方法可以做到这一点? 我认为numpy和itertools的组合应该会起作用 编辑: 答案很好,但他们是否认为X是一个矩阵?所以x1,x1,。。x3最终可以成为阵列吗 编辑: 一个真实的例子 a=array([[1,2,3],[4,5,6]]) 这应该是答案 a = [1, 2, 3] p

我有一个numpy矩阵X,我想把2列之间所有可能的乘积作为新变量添加到这个矩阵中

So if X=(x1,x2,x3) I want X=(x1,x2,x3,x1x2,x2x3,x1x3)
有没有一种优雅的方法可以做到这一点? 我认为numpy和itertools的组合应该会起作用

编辑: 答案很好,但他们是否认为X是一个矩阵?所以x1,x1,。。x3最终可以成为阵列吗

编辑: 一个真实的例子

a=array([[1,2,3],[4,5,6]])
这应该是答案

a = [1, 2, 3]
p = (x * y for x, y in itertools.combinations(a, 2))
print list(itertools.chain(a, p))
结果:

[1, 2, 3, 2, 3, 6] # 1, 2, 3, 2 x 1, 3 x 1, 3 x 2

我认为萨米的解决方案很好。如果需要使用numpy,可以对其进行如下转换:

from itertools import combinations
from numpy import prod

x = [1, 2, 3]
print x + map(prod, combinations(x, 2))
import numpy as np

def all_products2(a):
    x, y = np.triu_indices(len(a), 1)
    return np.r_[a, a[x] * a[y]]
提供与Samy的解决方案相同的输出:

[1, 2, 3, 2, 3, 6]

如果阵列很小,则可以使用:

from itertools import combinations, chain

def all_products1(a):
    p = (x * y for x, y in combinations(a, 2))
    return list(chain(a, p))
但是如果您的数组很大,那么您可以通过使用以下方法对计算进行完全矢量化,从而获得显著的加速:

from itertools import combinations
from numpy import prod

x = [1, 2, 3]
print x + map(prod, combinations(x, 2))
import numpy as np

def all_products2(a):
    x, y = np.triu_indices(len(a), 1)
    return np.r_[a, a[x] * a[y]]
让我们比较一下:

>data=np.random.uniform(01100,(10000,))
>>>timeit(lambda:all_products1(数据),数字=1)
53.745754408999346
>>>timeit(lambda:all_products2(数据),编号=1)
12.26144006299728
使用
numpy.triu\u索引的解决方案也适用于多维数据:

>np.随机.均匀(01100,(3,2))
数组([[63.75071196,15.19461254],
[ 94.33972762,  50.76916376],
[ 88.24056878,  90.36136808]])
>>>所有产品2(u)
数组([[63.75071196,15.19461254],
[   94.33972762,    50.76916376],
[   88.24056878,    90.36136808],
[ 6014.22480172,   771.41777239],
[ 5625.39908354,  1373.00597677],
[ 8324.59122432,  4587.57109368]])
如果要对列而不是行进行操作,请使用:

def all_products3(a):
    x, y = np.triu_indices(a.shape[1], 1)
    return np.c_[a, a[:,x] * a[:,y]]
例如:

>np.随机.均匀(01100,(2,3))
数组([[33.0062385,28.17575024,20.42504351],
[ 40.84235995,  61.12417428,  58.74835028]])
>>>所有产品3(u)
阵列([[33.0062385,28.17575024,20.425043511929.97553238,
674.15385734,   575.4909246 ],
[   40.84235995,    61.12417428,    58.74835028,  2496.45552756,
2399.42126888,  3590.94440122]])

我有一个大阵列,所以您的解决方案会很好。问题是您正在添加行。我想添加列。