Michael
Michael

Reputation: 3356

Pandas Series of lists from list of lists

Background

Given a list of lists (or numpy array of array):

array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ..., 
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]])

Question

How does one create a Pandas Series with an array in each row?

0       [0, 0, 0, ..., 0, 0, 0]
1       [0, 0, 0, ..., 0, 0, 0]
        ...  
999     [0, 0, 0, ..., 0, 0, 0]
1000    [0, 0, 0, ..., 0, 0, 0]

Attempt

df['my_array'] = pd.Series(my_array_of_arrays)

Traceback (most recent call last)
...
Exception: Data must be 1-dimensional

Upvotes: 2

Views: 3874

Answers (1)

EdChum
EdChum

Reputation: 394051

Cast to list so it stores each element as an array in the series:

In [112]:
a = np.array([[0,1,2],[2,3,5]])

Out[112]:
array([[0, 1, 2],
       [2, 3, 5]])

In [114]:    
pd.Series(list(a))

Out[114]:
0    [0, 1, 2]
1    [2, 3, 5]
dtype: object

You can see that the element is still an array:

In [116]:
pd.Series(list(a))[0]
Out[116]:
array([0, 1, 2])

Upvotes: 2

Related Questions