How to efficiently prepare matrices (2-dimensional array) for multiple arguments?

If you want to efficiently evaluate an array from 1 array for multiple arguments, i.e. without for-loop, you can do this:

x = array([1, 2, 3])
def gen_1d_arr(x):
    arr = array([2 + x, 2 - x,])
    return arr

gen_1d_arr(x).T

      

and you get:

array([[ 3,  1],
       [ 4,  0],
       [ 5, -1]])

      

Ok, but how do you do it for a 2-dimensional array like below:

def gen_2d_arr(x):
    arr = array([[2 + x, 2 - x,],
                 [2 * x, 2 / x]])
    return arr

      

and get it ?:

array([[[ 3.        ,  1.        ],
        [ 2.        ,  2.        ]],

       [[ 4.        ,  0.        ],
        [ 4.        ,  1.        ]],

       [[ 5.        , -1.        ],
        [ 6.        ,  0.66666667]]])

      

Also, is this possible for nd arrays?

+3


source to share


1 answer


See what you get with your function

In [274]: arr = np.array([[2 + x, 2 - x,],
                 [2 * x, 2 / x]])

In [275]: arr
Out[275]: 
array([[[ 3.        ,  4.        ,  5.        ],
        [ 1.        ,  0.        , -1.        ]],

       [[ 2.        ,  4.        ,  6.        ],
        [ 2.        ,  1.        ,  0.66666667]]])

In [276]: arr.shape
Out[276]: (2, 2, 3)

      

3

comes from x

. The middle 2

comes from the pairs [2+x, 2-x]

and the 1st 2

from the outer list.

It looks like you want an array (3,2,2). One option is to apply a transpose or axis anchor to arr

.



arr.transpose([2,0,1])

      

The main operation np.array([arr1,arr2])

is to build a new array with a new size in front, i.e. with a form (2, *arr1(shape))

.

There are other operations that combine arrays. np.concatenate

and its variants hstack

, vstack

, dstack

, column_stack

are combined arrays. .reshape()

and [None,...]

, atleast_nd

etc. add dimensions. Have a look at the function code stack

for some ideas on how to concatenate arrays using these tools.

In terms of efficiency, my timing tests show that concatenation operations are generally faster than np.array

. Frequently np.array

converts its inputs to lists and re-parses the values. This gives a lot of power in cooercing arrays for specific types, but at the expense of time. But I would only worry about this with large arrays where construction time is significant.

+2


source







All Articles