Home > Enterprise >  Error tuple index out of range for matrix preprocess
Error tuple index out of range for matrix preprocess

Time:02-22

I am trying to run user defined function to process matrices by adding a column with "1"

  def updated_x (input_x):
        if input_x.shape[0] < input_x.shape[1]:
            input_x = np.transpose(input_x)
          
        ones = np.ones((len(input_x), 1), dtype=int)
        updated_x = np.concatenate((ones, input_x), axis=1)
        return updated_x 

I have following input values:

input2 = np.array([5,4,6])
input1 = np.array([[5,4,8,9],[5,5,5,6]])
input3 = np.array([[2,4],[1,2],[2,3],[4,12]])

for i in [input1, input2, input3]:
            print(updated_x(i), )

I get error for 2 arrays out of three

[[ 1  2  4]
 [ 1  3  5]
 [ 1  6  7]
 [ 1  9 10]]

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-117-8fc2b754194b> in <module>
      1 for i in [input1, input2, input3]:
----> 2             print(updated_x(i), )

<ipython-input-115-41916a0377b0> in updated_x(input_x)
      4 
      5 def updated_x(input_x):
----> 6     if input_x.shape[0] < input_x.shape[1]:
      7         input_x = np.transpose(input_x)
      8 

IndexError: tuple index out of range

CodePudding user response:

input2 has shape (3,). Try to reshape it before function call:

input2 = input2.reshape(1,-1)

or otherwise add some check code at the very start of the function body:

def updated_x (input_x):

    if len(input_x.shape)<2:
        input_x = input_x.reshape(1,-1)
    #..........
    #..........
  • Related