Shape of passed values is (6, 4), indices imply (4, 4)

Question:

I’m trying to make a Pandasandas DataFrame the data is zeros with shape (6,4) and the columns are

col=['Example', 'Example', 'Example', 'Example']

and the index is a list of lists:

ind=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

and I’m doing it in this way:

pd.DataFrame(np.zeros((6,4)), columns = col, index=ind )

but it returns an error

Shape of passed values is (6, 4), indices imply (4, 1)

I tried to replace the list with a tuple and it worked! I’m wandering why this error is happening and how to solve it

Asked By: Karam

||

Answers:

You will need to pass an immutable object as index so that the index considers 6 indexes. You can do that by converting each of the sublists as tuples [tuple(i) for i in ind]

ind=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
col=['Example', 'Example', 'Example', 'Example']
pd.DataFrame(np.zeros((6,4)), columns = col, index=[tuple(i) for i in ind])
              Example  Example  Example  Example
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0

You could create a multi-index out of this so that the index has 4 levels.

ind=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
col=['Example', 'Example', 'Example', 'Example']
print(pd.DataFrame(np.zeros((6,4)), columns = col, index=pd.MultiIndex.from_tuples(ind)))
         Example  Example  Example  Example
1 2 3 4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0

#Here first level is all 1 and second level is all 2 (and so on...)
Answered By: Akshay Sehgal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.