Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python all possible products between columns

I have a numpy matrix X and I would like to add to this matrix as new variables all the possible products between 2 columns.

So if X=(x1,x2,x3) I want X=(x1,x2,x3,x1x2,x2x3,x1x3)

Is there an elegant way to do that? I think a combination of numpy and itertools should work

EDIT: Very good answers but are they considering that X is a matrix? So x1,x1,.. x3 can eventually be arrays?

EDIT: A Real example

a=array([[1,2,3],[4,5,6]])
like image 897
Donbeo Avatar asked Feb 14 '23 16:02

Donbeo


1 Answers

Itertools should be the answer here.

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

Result:

[1, 2, 3, 2, 3, 6] # 1, 2, 3, 2 x 1, 3 x 1, 3 x 2
like image 177
Samy Arous Avatar answered Feb 17 '23 01:02

Samy Arous