Skip to content Skip to sidebar Skip to footer

Flatten Out Indices In Order To Access Elements?

Let's say I have : one = np.array([ [2,3,np.array([ [1,2], [7,3] ])], [4,5,np.array([ [11,12],[14,15] ])] ], dtype=object) two = np.array([ [1,

Solution 1:

This works

np.r_[tuple(one[:, 2])] == two

Output:

array([[ True,  True],
       [ True,  True],
       [ True,  True],
       [ True,  True]], dtype=bool)

Solution 2:

In a comment link @George tried to work with:

In[246]: aOut[246]: array([1, [2, [33, 44, 55, 66]], 11, [22, [77, 88, 99, 100]]], dtype=object)
In[247]: a.shapeOut[247]: (4,)

This is a 4 element array. If we reshape it, we can isolate an inner layer

In [257]: a.reshape(2,2)
Out[257]: 
array([[1, [2, [33, 44, 55, 66]]],
       [11, [22, [77, 88, 99, 100]]]], dtype=object)
In [258]: a.reshape(2,2)[:,1]
Out[258]: array([[2, [33, 44, 55, 66]], [22, [77, 88, 99, 100]]], dtype=object)

This last case is (2,) - 2 lists. We can isolate the 2nd item in each list with a comprehension, and create an array from the resulting lists:

In [260]: a1=a.reshape(2,2)[:,1]
In [261]: [i[1] for i in a1]
Out[261]: [[33, 44, 55, 66], [77, 88, 99, 100]]
In [263]: np.array([i[1] for i in a1])
Out[263]: 
array([[ 33,  44,  55,  66],
       [ 77,  88,  99, 100]])

Nothing fancy here - just paying attention to array shapes, and using list operations where arrays don't work.

Post a Comment for "Flatten Out Indices In Order To Access Elements?"