Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert matrix to pandas data frame

Tags:

python

pandas

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.

like image 703
Hangon Avatar asked Nov 06 '14 11:11

Hangon


2 Answers

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
like image 108
greole Avatar answered Oct 10 '22 21:10

greole


Well, I was wondering if we could use python's multi-dimensional array. Yes, you can use python matrix (as mentioned in the python official docs) or multi-dimensional arrays and convert into pandas DataFrame.

import pandas as pd
matrix = [
    ["a", 1],
    ["b", 2]
]
pd.DataFrame(matrix)

   0  1
0  a  1
1  b  2
like image 33
mythicalcoder Avatar answered Oct 10 '22 20:10

mythicalcoder