0

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

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Karam
  • 17
  • 5

1 Answers1

0

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...)
Marceli Wac
  • 375
  • 3
  • 13
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51