Home > Enterprise >  Python indexing question - 'IndexError: too many indices for array: array is 1-dimensional, but
Python indexing question - 'IndexError: too many indices for array: array is 1-dimensional, but

Time:11-18

Please can someone tell me why the following code does not work, and what the best work arounds for this are?

Choices # variable containing True or False in each element.
Choices.shape = (18978,)
BestOption # variable containing 1 or 2 in each element.
BestOption.shape = (18978, 1)

Choices[BestOption==1] # I want to look up the values in choices for all instances where BestOption is 1.

I get the following error:

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

CodePudding user response:

BestOption is a 1-D "column vector" that's actually made up of many rows and is treated like a 2-D matrix. You can simply reshape it back to a 1-D "row vector":

Choices[BestOption.reshape(-1)==1]
  • Related