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.
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
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
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