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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With