Hangon Hangon - 24 days ago 12
Python Question

How to convert matrix to pandas data frame

I'm trying to convert a matrix into a pandas data frame:

matrixA={}
matrixA[0,0]='a'
matrixA[0,1]='b'
matrixA[1,0]='c'
matrixA[1,1]='d'


Like this:

import pandas as pd

pd.DataFrame(matrixA)


I get an error.

Answer

As already said your are not creating a matrix but a python dictionary. However a dict can serve as parameter to create a dataframe, but you reversed the indexing order.

import pandas as pd

matrixA={}
matrixA['a']=[0,0]
matrixA['b']=[0,1]

pd.DataFrame(matrixA)

   a  b
0  0  0
1  0  1

Additionally you can use numpys matrix

import numpy as np

a = np.matrix('1 2; 3 4')
pd.DataFrame(a)

   0  1
0  1  2
1  3  4
Comments