4

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks "Bas Swinckles". Are there any quick tutorials for this?
I added a link to Numpy's tutorial.
1

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

1 Comment

Thanks Jaime, I am a newbie to numpy, was going the python comprehension path. I think this is cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.