numpy IndexError: too many indices for array when indexing matrix with another

2024/10/7 4:37:04

I have a matrix a which I create like this:

>>> a = np.matrix("1 2 3; 4 5 6; 7 8 9; 10 11 12")

I have a matrix labels which I create like this:

>>> labels = np.matrix("1;0;1;1")

This is what the two matricies look like:

>>> a
matrix([[ 1,  2,  3],[ 4,  5,  6],[ 7,  8,  9],[10, 11, 12]])
>>> labels
matrix([[1],[0],[1],[1]])

As you can see, when I select all columns, there is no problem

>>> a[labels == 1, :]
matrix([[ 1,  7, 10]])

But when I try to specify a column I get an error

>>> a[labels == 1, 1]
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/usr/local/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 305, in     __getitem__out = N.ndarray.__getitem__(self, index)
IndexError: too many indices for array
>>>   

Does anybody know why this is? I am aware there are similar questions to this already but none of them explain my problem well enough, neither are the answers helpful to me.

Answer

Since labels is a matrix when you do labels==1 you obtain a boolean matrix of the same shape. Then doing a[labels==1, :] will return you only the first column with the lines corresponding to the match. Note that your intention to get:

matrix([[ 1,  2,  3],[ 7,  8,  9],[10, 11, 12]])

was not achieved (you got only the first column), even though it worked for NumPy < 1.8 (as pointed out by @seberg).

In order to get what you want you can use a flattened view of labels:

a[labels.view(np.ndarray).ravel()==1, :]
https://en.xdnf.cn/q/70282.html

Related Q&A

how to use enum in swig with python?

I have a enum declaration as follows:typedef enum mail_ {Out = 0,Int = 1,Spam = 2 } mail;Function:mail status; int fill_mail_data(int i, &status);In the function above, status gets filled up and wi…

What does except Exception as e mean in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 4…

Numpy efficient big matrix multiplication

To store big matrix on disk I use numpy.memmap.Here is a sample code to test big matrix multiplication:import numpy as np import timerows= 10000 # it can be large for example 1kk cols= 1000#create some…

Basic parallel python program freezes on Windows

This is the basic Python example from https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool on parallel processingfrom multiprocessing import Pooldef f(x):return x*xif __na…

Formatting multiple worksheets using xlsxwriter

How to copy the same formatting to different sheets of the same Excel file using the xlsxwriter library in Python?The code I tried is: import xlsxwriterimport pandas as pd import numpy as npfrom xlsxw…

Good python library for generating audio files? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Keras ConvLSTM2D: ValueError on output layer

I am trying to train a 2D convolutional LSTM to make categorical predictions based on video data. However, my output layer seems to be running into a problem:"ValueError: Error when checking targe…

debugging argpars in python

May I know what is the best practice to debug an argpars function.Say I have a py file test_file.py with the following lines# Script start import argparse import os parser = argparse.ArgumentParser() p…

Non-blocking server in Twisted

I am building an application that needs to run a TCP server on a thread other than the main. When trying to run the following code:reactor.listenTCP(ServerConfiguration.tcpport, TcpCommandFactory()) re…

Reading changing file in Python 3 and Python 2

I was trying to read a changing file in Python, where a script can process newly appended lines. I have the script below which prints out the lines in a file and does not terminate.with open(tmp.txt,r)…