Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/66046235/shape-of-passed-values-is-6-4-indices-imply-4-4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will need to pass an immutable object as index so that the index considers 6 indexes. You cna 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...