user3768495 user3768495 - 6 days ago 7
Python Question

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

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

If, for some reason, you have found yourself with that abomination of a Series, getting it back into the sort of matrix or array you want is straightforward:

In [16]: s
Out[16]:
0     [1, 2, 3]
1     [2, 3, 4]
2     [3, 4, 5]
3     [2, 3, 4]
4     [3, 4, 5]
5     [2, 3, 4]
6     [3, 4, 5]
7     [2, 3, 4]
8     [3, 4, 5]
9     [2, 3, 4]
10    [3, 4, 5]
dtype: object

In [17]: sm = np.matrix(s.tolist())

In [18]: sm
Out[18]:
matrix([[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]])

In [19]: sm.shape
Out[19]: (11, 3)

But unless it's something you can't change, having that Series makes little sense to begin with.

Comments