tcapelle
tcapelle

Reputation: 490

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?

Upvotes: 6

Views: 3972

Answers (1)

jezrael
jezrael

Reputation: 862681

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

Upvotes: 7

Related Questions