Reputation:
I want to initializes a dataframe and set its column and index as shown below but I face some issues while do like this:
pd1 = pd.DataFrame(Matrix, columns=da, index=cl)
From above Matrix define as:
Matrix = [[[0], [0], [0]],
[[0], [0], [0]]]
and da as:
da = ['A','B']
and cl as:
cl = ['X','Y','Z']
following error is occur while executing this line:
# caller's responsibility to check for this..
raise AssertionError('%d columns passed, passed data had %s '
'columns' % (len(columns), len(content)))
# provide soft conversion of object dtypes
AssertionError: 2 columns passed, passed data had 3 columns
how to resolve this problem in python dataframe?
Upvotes: 1
Views: 12838
Reputation: 50200
Make a dataframe without indices and you'll discover that pandas
interprets your matrix row-wise:
>>> df = pd.DataFrame(Matrix)
>>> df
0 1 2
0 [0] [0] [0]
1 [0] [0] [0]
So you need to transpose your data (or swap the columns
and index
arguments). This does the job:
>>> df = pd.DataFrame(Matrix, index=da, columns=cl).transpose()
>>> df
A B
X [0] [0]
Y [0] [0]
Z [0] [0]
PS. I wonder if you really want the brackets around each value. But maybe you have a reason...
Upvotes: 3