Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy matrix to pandas Series

This is a simple question: I have a numpy matrix A that I would like to convert to a column in a data frame (a Series), preserving the multindexing of the matrix. By this I mean, the i,j position in the matrix to be converted to i, j row indexing in pandas.

In [68]: A = np.array([[1,2],[3,4]])

Take this matrix, some voodoo magic and get this:

In [69]: Series([1,2,3,4],index = [[0,0,1,1],[0,1,0,1]])
Out[69]: 
0  0    1
   1    2
1  0    3
   1    4
dtype: int64

Is there a way to do this?

like image 547
tcapelle Avatar asked Apr 28 '16 13:04

tcapelle


1 Answers

You can use stack with DataFrame constructor:

import pandas as pd
import numpy as np

print pd.DataFrame(np.array([[1,2],[3,4]])).stack()

0  0    1
   1    2
1  0    3
   1    4
dtype: int32
like image 136
jezrael Avatar answered Nov 15 '22 04:11

jezrael