Force number to save list

x2_Kaxs- an array of Nx3 numpy lists, and elements in these lists are indexed into another array. I want to get an array of Nx3 numpy lists of these indexed items.

x2_Kcids = array([ ax2_cid[axs] for axs in x2_Kaxs.flat ], dtype=object)

This outputs an array of numpy (N * 3) x1 arrays. Great. which almost works for what i want. All I have to do is change it.

x2_Kcids.shape = x2_Kaxs.shape

And it works. x2_Kcidsbecomes an array of Nx3 numpy arrays. Fine.

With the exception of all lists in x2_Kaxs, they have only one item. Then it smoothes this into an Nx3 integer array, and my code expects a list later in the pipeline.

One solution that I came up with was to add a dummy element and then pop up, but it is very ugly. Is there anything nicer?

+5
2

, 1, . :

ax2_cid = np.random.rand(10)
shape = (10, 3)

x2_Kaxs = np.empty((10, 3), dtype=object).reshape(-1)
for j in xrange(x2_Kaxs.size):
    x2_Kaxs[j] = [random.randint(0, 9) for k in xrange(random.randint(1, 5))]
x2_Kaxs.shape = shape

x2_Kaxs_1 = np.empty((10, 3), dtype=object).reshape(-1)
for j in xrange(x2_Kaxs.size):
    x2_Kaxs_1[j] = [random.randint(0, 9)]
x2_Kaxs_1.shape = shape

x2_Kaxs_2 = np.empty((10, 3), dtype=object).reshape(-1)
for j in xrange(x2_Kaxs_2.size):
    x2_Kaxs_2[j] = [random.randint(0, 9) for k in xrange(2)]
x2_Kaxs_2.shape = shape

, :

>>> np.array([ax2_cid[axs] for axs in x2_Kaxs.flat], dtype=object).shape
(30,)
>>> np.array([ax2_cid[axs] for axs in x2_Kaxs_1.flat], dtype=object).shape
(30, 1)
>>> np.array([ax2_cid[axs] for axs in x2_Kaxs_2.flat], dtype=object).shape
(30, 2)

2 (n, 3). , dtype=object numpy , , . , , x2_Kcids:

x2_Kcids = np.empty_like(x2_Kaxs).reshape(-1)
shape = x2_Kaxs.shape
x2_Kcids[:] = [ax2_cid[axs] for axs in x2_Kaxs.flat]
x2_Kcids.shape = shape

unubtu , . :

x2_Kcids = np.empty_like(x2_Kaxs)
x2_Kcids.ravel()[:] = [ax2_cid[axs] for axs in x2_Kaxs.flat]

:

>>> x2_Kcids_1 = np.empty_like(x2_Kaxs_1).reshape(-1)
>>> x2_Kcids_1[:] = [ax2_cid[axs] for axs in x2_Kaxs_1.flat]
>>> x2_Kcids_1.shape = shape
>>> x2_Kcids_1
array([[[ 0.37685372], [ 0.95328117], [ 0.63840868]],
       [[ 0.43009678], [ 0.02069558], [ 0.32455781]],
       [[ 0.32455781], [ 0.37685372], [ 0.09777559]],
       [[ 0.09777559], [ 0.37685372], [ 0.32455781]],
       [[ 0.02069558], [ 0.02069558], [ 0.43009678]],
       [[ 0.32455781], [ 0.63840868], [ 0.37685372]],
       [[ 0.63840868], [ 0.43009678], [ 0.25532799]],
       [[ 0.02069558], [ 0.32455781], [ 0.09777559]],
       [[ 0.43009678], [ 0.37685372], [ 0.63840868]],
       [[ 0.02069558], [ 0.17876822], [ 0.17876822]]], dtype=object)
>>> x2_Kcids_1[0, 0]
array([ 0.37685372])
+2

@Denis:

if x.ndim == 2:
    x.shape += (1,)
0

All Articles