0

I am missing something simple here. I cannot figure out how to pass multiple columns of a 2D array (matrix) and output them as a single column array.

Here is a simple example:

import numpy as np

Z = lambda x1,x2: (x1*x2 - 3)^2 + 1

# a sample 2D array with 15 rows and 2 columns    
x= np.arange(30).reshape((15,2))

answer = [Z(i[0],i[1]) for i in x]

The last line of code is where my problem lies. I would like the output to be a single column array with 15 rows.

As a final note: My code only uses 2 columns as inputs. If it could be further expanded to a flexible number of columns, it would be greatly appreciated.

2
  • In the end I don't know what you want to do, but are you aware that you could do the same operation with numpy leaving out the for loop? which would be: (x[:,0]*x[:,1] -3 )^2 + 1. Also x*x would be x**2 instead of x^2 (if you were intentionally doing that please forgive me) Commented Apr 1, 2014 at 11:05
  • 1
    Oh and if you really need columns you could do ((x[:,0]*x[:,1] -3 )^2 + 1)[np.newaxis,:] Commented Apr 1, 2014 at 11:13

2 Answers 2

1

Could you make your last line:

answer = np.array([Z(i[0],i[1]) for i in x]).reshape(15,1)

which gives:

array([[ -2],
       [  0],
       [ 18],
       [ 36],
       [ 70],
       [104],
       [154],
       [204],
       [270],
       [336],
       [418],
       [500],
       [598],
       [696],
       [810]])
Sign up to request clarification or add additional context in comments.

2 Comments

If you wanted to get rid of the 15 (because the size of the array might change) you could also do .reshape(-1,1) or np.array([[Z(i[0],i[1]) for i in x]]) (note the double [[ ]])
As a note numpy strives to avoid explicit for loops. Using numpy in this way will actually slow down your calculation.
1

You could do

import numpy as np

Z = lambda data, i, j: ((data[:,i]*data[:,j] - 3)**2 + 1)[:,np.newaxis]

# a sample 2D array with 15 rows and 2 columns    
x= np.arange(30).reshape((15,2))

answer = Z(x,0,1)

so maybe you don't need the lambda function after all

Comments

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.