How to convert a series of arrays into one matrix in pandas / numpy?

I somehow got pandas.Seriesone that contains a set of arrays, as sin 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 to convert sto a matrix with the form (11.3)? Thank!

+4
source share
2 answers

If for some reason you find yourself with this abomination Series, returning it to the type matrixor arraythat you need, it's simple:

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 if this is not something you cannot change, with this series it makes little sense to start with.

+4
source

numpy.stack .

np.stack(s.values)

PS. .

0

Source: https://habr.com/ru/post/1662046/


All Articles