python - Find shape of numpy array with differing column lengths -


what want find length of every column in 2d numpy array.

if columns have same length, trivial numpy.shape, if columns have different lengths numpy.shape doesn't tell me lengths of different columns.

a=np.asarray([[0,1],[0,1],[0,1]]) b=np.asarray([[0,1],[0,1,2],[0]]) a.shape,b.shape ((3,2), (3,)) 

i can want doing like,

lenb=[len(b) b in b] [2, 3, 1] 

but feel there must cleaner , quicker way numpy.

your b object array - 1d list elements. actions on array require list comprehension or map.

array([[0, 1], [0, 1, 2], [0]], dtype=object) 

that 'object' dtype divides array operations list ones. shape array property. len() closest list function, has applied each element separately.

in py3, prefer clarity of list comprehension map, that's preference. functionally it's same thing:

in [30]: [len(i) in b] out[30]: [2, 3, 1] in [31]: list(map(len,b)) out[31]: [2, 3, 1] 

there possibility:

in [32]: np.frompyfunc(len,1,1)(b) out[32]: array([2, 3, 1], dtype=object) 

you change elements of b other objects len

in [39]: b[0]='abcd'    # string in [43]: b[2]={1,2,1,3,4}   # set in [44]: b out[44]: array(['abcd', [0, 1, 2], {1, 2, 3, 4}], dtype=object) in [45]: [len(i) in b] out[45]: [4, 3, 4] 

this should highlight fact len property of elements, not array or 'columns' (which doesn't have).


Comments