how to convert a Series of arrays into a single matrix in pandas/numpy?

user3768495 picture user3768495 · Nov 27, 2016 · Viewed 12k times · Source

I somehow got a pandas.Series which contains a bunch of arrays in it, as the s in the code below.

data = [[1,2,3],[2,3,4],[3,4,5],[2,3,4],[3,4,5],[2,3,4],
        [3,4,5],[2,3,4],[3,4,5],[2,3,4],[3,4,5]]
s = pd.Series(data = data)
s.shape # output ---> (11L,)
# try to convert s to matrix
sm = s.as_matrix()
# but...
sm.shape # output ---> (11L,)

How can I convert the s into a matrix with shape (11,3)? Thanks!

Answer

Selah picture Selah · Feb 14, 2018

Another way is to extract the values of your series and use numpy.stack on them.

np.stack(s.values)

PS. I've run into similar situations often.