简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM