pramodh
pramodh

Reputation: 1329

transforming a numpy array

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.

Upvotes: 4

Views: 1293

Answers (2)

Bas Swinckels
Bas Swinckels

Reputation: 18508

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.

Upvotes: 5

Jaime
Jaime

Reputation: 67507

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]])

Upvotes: 1

Related Questions