I have a list of lists (of variable len) that needs to be converted into a numpy array. Example:
import numpy as np
sample_list = [["hello", "world"], ["foo"], ["alpha", "beta", "gamma"], []]
sample_arr = np.asarray(sample_list)
>>> sample_arr
array([list(['hello', 'world']), list(['foo']),
list(['alpha', 'beta', 'gamma']), list([])], dtype=object)
>>> sample_arr.shape
(4,)
In the above example, I got a single-dimensional array which is desired. The downstream modules of the code expect the same. However when the lists have the same length, it outputting a 2-dimensional array resulting in error in downstream modules of my code:
sample_list = [["hello"], ["world"], ["foo"], ["bar"]]
sample_arr = np.asarray(sample_list)
>>>
>>> sample_arr
array([['hello'],
['world'],
['foo'],
['bar']], dtype='<U5')
>>> sample_arr.shape
(4, 1)
Instead, I wanted the output similar to the first example:
>>> sample_arr
array([list(['hello']), list(['world']),
list(['foo']), list(['bar'])], dtype=object)
Is there any way I can achieve that?