Reputation: 7
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.
Upvotes: 0
Views: 3912
Reputation: 2573
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
Upvotes: 1
Reputation: 31050
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]])
Upvotes: 1