transforming a numpy array

Question:

I have a numpy array of this form

[[-0.77947021  0.83822138]
[ 0.15563491  0.89537743]
[-0.0599077  -0.71777995]
[ 0.20759636  0.75893338]]

I want to create numpy array of this form [x1, x2, x1*x2] where [x1, x2] are from the original array list.

At the moment I am creating a list of list using python code, then converting it to numpy array. But I think there might be a better way to do this.

Asked By: pramodh

||

Answers:

Like so:

In [22]: import numpy as np

In [23]: x = np.array([[-0.77947021,  0.83822138],
    ...: [ 0.15563491,  0.89537743],
    ...: [-0.0599077,  -0.71777995],
    ...: [ 0.20759636,  0.75893338]])

In [24]: np.c_[x, x[:,0] * x[:,1]]
Out[24]: 
array([[-0.77947021,  0.83822138, -0.6533686 ],
       [ 0.15563491,  0.89537743,  0.13935199],
       [-0.0599077 , -0.71777995,  0.04300055],
       [ 0.20759636,  0.75893338,  0.15755181]])

This uses numpy.c_, which is a convenience function to concatenate various arrays along their second dimension.

You can find some more info about concatenating arrays in Numpy’s tutorial. Functions like hstack (see Jaime’s answer), vstack, concatenate, row_stack and column_stack are probably the ‘official’ functions you should use. The functions r_ and c_ are a bit of hack to simulate some of Matlab’s functionality. They are a bit ugly, but allow you write a bit more compactly.

Answered By: Bas Swinckels

There’s a million different ways, I’d probably go with this:

>>> x = np.random.rand(5, 2)
>>> np.hstack((x, np.prod(x, axis=1, keepdims=True)))
array([[ 0.39614232,  0.14416164,  0.05710853],
       [ 0.75068436,  0.61687739,  0.46308021],
       [ 0.90181541,  0.20365294,  0.18365736],
       [ 0.08172452,  0.36334486,  0.02969418],
       [ 0.61455203,  0.80694432,  0.49590927]])
Answered By: Jaime
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.