Finding index of the element in a numpy array witout using for loopFinding which rows have all elements as zeros in a matrix with numpyFinding the index of an item given a list containing it in PythonDeleting an element from an array in PHPAccessing the index in 'for' loops?How to insert an item into an array at a specific index (JavaScript)?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()Swift for loop: for index, element in array?Finding the index of a numpy array in a list

Teaching a class likely meant to inflate the GPA of student athletes

Why does this query, missing a FROM clause, not error out?

Is it possible to have 2 different but equal size real number sets that have the same mean and standard deviation?

How to communicate to my GM that not being allowed to use stealth isn't fun for me?

How to “listen” to existing circuit

How can I end combat quickly when the outcome is inevitable?

Are there any normal animals in Pokemon universe?

Live action TV show where High school Kids go into the virtual world and have to clear levels

Is it expected that a reader will skip parts of what you write?

Why did Intel abandon unified CPU cache?

What are neighboring ports?

Can the removal of a duty-free sales trolley result in a measurable reduction in emissions?

Plural or singular in lists

Is there a set of positive integers of density 1 which contains no infinite arithmetic progression?

Why not invest in precious metals?

How to you show a 3-center 2-electron bond in a Lewis structure?

How to safely destroy (a large quantity of) valid checks?

Insert external file and modify each line from script

What should I write in an apology letter, since I have decided not to join a company after accepting an offer letter

How can one's career as a reviewer be ended?

Can a human be transformed into a Mind Flayer?

How to learn Linux system internals

Does Assassinate grant two attacks?

Why are MBA programs closing?



Finding index of the element in a numpy array witout using for loop


Finding which rows have all elements as zeros in a matrix with numpyFinding the index of an item given a list containing it in PythonDeleting an element from an array in PHPAccessing the index in 'for' loops?How to insert an item into an array at a specific index (JavaScript)?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()Swift for loop: for index, element in array?Finding the index of a numpy array in a list






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















As an input i have 2d numpy array, lets suppose this one:



my_array = np.matrix([[3, 7, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]])


I have to find the index of every element in that array in which the sum of elements in that row and column == 0. In this case, the answer would be (2, 3), since the sum of elements in second row = 0 and sum of elements in 3rd column = 0. So far i came up with this:



solution = [(i, j) for i in range(my_array.shape[0]) for j in range(my_array.shape[1]) if 1 not in my_array[i] and 1 not in my_array[:, j]]


The problem is, I want to do this without using for loop.



I've tried using np.where and np.sum, ended up with this:



np.where(np.sum(my_array, axis=1) == 0 and np.sum(my_array, axis=0) == 0)


but i end up with this error:



ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Any suggestion about how can i fix this error or just use other method to find the indexes?










share|improve this question

















  • 1





    Possible duplicate of Finding which rows have all elements as zeros in a matrix with numpy

    – aws_apprentice
    Mar 24 at 20:04

















1















As an input i have 2d numpy array, lets suppose this one:



my_array = np.matrix([[3, 7, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]])


I have to find the index of every element in that array in which the sum of elements in that row and column == 0. In this case, the answer would be (2, 3), since the sum of elements in second row = 0 and sum of elements in 3rd column = 0. So far i came up with this:



solution = [(i, j) for i in range(my_array.shape[0]) for j in range(my_array.shape[1]) if 1 not in my_array[i] and 1 not in my_array[:, j]]


The problem is, I want to do this without using for loop.



I've tried using np.where and np.sum, ended up with this:



np.where(np.sum(my_array, axis=1) == 0 and np.sum(my_array, axis=0) == 0)


but i end up with this error:



ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Any suggestion about how can i fix this error or just use other method to find the indexes?










share|improve this question

















  • 1





    Possible duplicate of Finding which rows have all elements as zeros in a matrix with numpy

    – aws_apprentice
    Mar 24 at 20:04













1












1








1








As an input i have 2d numpy array, lets suppose this one:



my_array = np.matrix([[3, 7, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]])


I have to find the index of every element in that array in which the sum of elements in that row and column == 0. In this case, the answer would be (2, 3), since the sum of elements in second row = 0 and sum of elements in 3rd column = 0. So far i came up with this:



solution = [(i, j) for i in range(my_array.shape[0]) for j in range(my_array.shape[1]) if 1 not in my_array[i] and 1 not in my_array[:, j]]


The problem is, I want to do this without using for loop.



I've tried using np.where and np.sum, ended up with this:



np.where(np.sum(my_array, axis=1) == 0 and np.sum(my_array, axis=0) == 0)


but i end up with this error:



ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Any suggestion about how can i fix this error or just use other method to find the indexes?










share|improve this question














As an input i have 2d numpy array, lets suppose this one:



my_array = np.matrix([[3, 7, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]])


I have to find the index of every element in that array in which the sum of elements in that row and column == 0. In this case, the answer would be (2, 3), since the sum of elements in second row = 0 and sum of elements in 3rd column = 0. So far i came up with this:



solution = [(i, j) for i in range(my_array.shape[0]) for j in range(my_array.shape[1]) if 1 not in my_array[i] and 1 not in my_array[:, j]]


The problem is, I want to do this without using for loop.



I've tried using np.where and np.sum, ended up with this:



np.where(np.sum(my_array, axis=1) == 0 and np.sum(my_array, axis=0) == 0)


but i end up with this error:



ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Any suggestion about how can i fix this error or just use other method to find the indexes?







python arrays python-3.x numpy






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 19:50









ArtismArtism

184




184







  • 1





    Possible duplicate of Finding which rows have all elements as zeros in a matrix with numpy

    – aws_apprentice
    Mar 24 at 20:04












  • 1





    Possible duplicate of Finding which rows have all elements as zeros in a matrix with numpy

    – aws_apprentice
    Mar 24 at 20:04







1




1





Possible duplicate of Finding which rows have all elements as zeros in a matrix with numpy

– aws_apprentice
Mar 24 at 20:04





Possible duplicate of Finding which rows have all elements as zeros in a matrix with numpy

– aws_apprentice
Mar 24 at 20:04












2 Answers
2






active

oldest

votes


















2














The problem with your where expression occurs inside it, in your attempt to combine two conditions:



In [210]: np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0 
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-210-46c837435a31> in <module>
----> 1 np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [211]: (np.sum(arr, axis=1) == 0) & (np.sum(arr, axis=0) == 0)
Out[211]: array([False, False, False, False])


You have to wrap the == test inside () so it occurs first, and you have to use & to perform element-wise and. and is a scalar operation, and does not play well with boolean arrays.



The row and column tests are:



In [212]: arr.sum(0)==0 
Out[212]: array([False, False, False, True])
In [213]: arr.sum(1)==0
Out[213]: array([False, False, True, False])


but you want a kind of outer or cartesian combination, not a simple element-wise combination (that would be more obvious if there were different numbers of rows and columns).



In [218]: (arr.sum(1)==0)[:,None] & (arr.sum(0)==0) 
Out[218]:
array([[False, False, False, False],
[False, False, False, False],
[False, False, False, True],
[False, False, False, False]])
In [219]: np.where(_)
Out[219]: (array([2]), array([3]))


Or with the keepdims parameter of sum:



In [220]: arr.sum(0, keepdims=True)==0 
Out[220]: array([[False, False, False, True]])
In [221]: arr.sum(1, keepdims=True)==0
Out[221]:
array([[False],
[False],
[ True],
[False]])
In [222]: np.where(_220 & _221) # Out[220] etc
Out[222]: (array([2]), array([3]))





share|improve this answer






























    0














    Here is a solution using product from itertools. Creating a list of rows and columns with sums == 0 and finding the combinations between them.



    from itertools import product

    my_array = np.matrix([[3, 7, 0, 0],
    [0, 2, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 1, 0]])


    a = np.argwhere(my_array.sum(axis = 1) == 0)[:,0]
    b = np.argwhere(my_array.sum(axis = 0) == 0)[:,1]

    np.array(list(product(a,b)))





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327903%2ffinding-index-of-the-element-in-a-numpy-array-witout-using-for-loop%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      The problem with your where expression occurs inside it, in your attempt to combine two conditions:



      In [210]: np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0 
      ---------------------------------------------------------------------------
      ValueError Traceback (most recent call last)
      <ipython-input-210-46c837435a31> in <module>
      ----> 1 np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0

      ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
      In [211]: (np.sum(arr, axis=1) == 0) & (np.sum(arr, axis=0) == 0)
      Out[211]: array([False, False, False, False])


      You have to wrap the == test inside () so it occurs first, and you have to use & to perform element-wise and. and is a scalar operation, and does not play well with boolean arrays.



      The row and column tests are:



      In [212]: arr.sum(0)==0 
      Out[212]: array([False, False, False, True])
      In [213]: arr.sum(1)==0
      Out[213]: array([False, False, True, False])


      but you want a kind of outer or cartesian combination, not a simple element-wise combination (that would be more obvious if there were different numbers of rows and columns).



      In [218]: (arr.sum(1)==0)[:,None] & (arr.sum(0)==0) 
      Out[218]:
      array([[False, False, False, False],
      [False, False, False, False],
      [False, False, False, True],
      [False, False, False, False]])
      In [219]: np.where(_)
      Out[219]: (array([2]), array([3]))


      Or with the keepdims parameter of sum:



      In [220]: arr.sum(0, keepdims=True)==0 
      Out[220]: array([[False, False, False, True]])
      In [221]: arr.sum(1, keepdims=True)==0
      Out[221]:
      array([[False],
      [False],
      [ True],
      [False]])
      In [222]: np.where(_220 & _221) # Out[220] etc
      Out[222]: (array([2]), array([3]))





      share|improve this answer



























        2














        The problem with your where expression occurs inside it, in your attempt to combine two conditions:



        In [210]: np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0 
        ---------------------------------------------------------------------------
        ValueError Traceback (most recent call last)
        <ipython-input-210-46c837435a31> in <module>
        ----> 1 np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0

        ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
        In [211]: (np.sum(arr, axis=1) == 0) & (np.sum(arr, axis=0) == 0)
        Out[211]: array([False, False, False, False])


        You have to wrap the == test inside () so it occurs first, and you have to use & to perform element-wise and. and is a scalar operation, and does not play well with boolean arrays.



        The row and column tests are:



        In [212]: arr.sum(0)==0 
        Out[212]: array([False, False, False, True])
        In [213]: arr.sum(1)==0
        Out[213]: array([False, False, True, False])


        but you want a kind of outer or cartesian combination, not a simple element-wise combination (that would be more obvious if there were different numbers of rows and columns).



        In [218]: (arr.sum(1)==0)[:,None] & (arr.sum(0)==0) 
        Out[218]:
        array([[False, False, False, False],
        [False, False, False, False],
        [False, False, False, True],
        [False, False, False, False]])
        In [219]: np.where(_)
        Out[219]: (array([2]), array([3]))


        Or with the keepdims parameter of sum:



        In [220]: arr.sum(0, keepdims=True)==0 
        Out[220]: array([[False, False, False, True]])
        In [221]: arr.sum(1, keepdims=True)==0
        Out[221]:
        array([[False],
        [False],
        [ True],
        [False]])
        In [222]: np.where(_220 & _221) # Out[220] etc
        Out[222]: (array([2]), array([3]))





        share|improve this answer

























          2












          2








          2







          The problem with your where expression occurs inside it, in your attempt to combine two conditions:



          In [210]: np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0 
          ---------------------------------------------------------------------------
          ValueError Traceback (most recent call last)
          <ipython-input-210-46c837435a31> in <module>
          ----> 1 np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0

          ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
          In [211]: (np.sum(arr, axis=1) == 0) & (np.sum(arr, axis=0) == 0)
          Out[211]: array([False, False, False, False])


          You have to wrap the == test inside () so it occurs first, and you have to use & to perform element-wise and. and is a scalar operation, and does not play well with boolean arrays.



          The row and column tests are:



          In [212]: arr.sum(0)==0 
          Out[212]: array([False, False, False, True])
          In [213]: arr.sum(1)==0
          Out[213]: array([False, False, True, False])


          but you want a kind of outer or cartesian combination, not a simple element-wise combination (that would be more obvious if there were different numbers of rows and columns).



          In [218]: (arr.sum(1)==0)[:,None] & (arr.sum(0)==0) 
          Out[218]:
          array([[False, False, False, False],
          [False, False, False, False],
          [False, False, False, True],
          [False, False, False, False]])
          In [219]: np.where(_)
          Out[219]: (array([2]), array([3]))


          Or with the keepdims parameter of sum:



          In [220]: arr.sum(0, keepdims=True)==0 
          Out[220]: array([[False, False, False, True]])
          In [221]: arr.sum(1, keepdims=True)==0
          Out[221]:
          array([[False],
          [False],
          [ True],
          [False]])
          In [222]: np.where(_220 & _221) # Out[220] etc
          Out[222]: (array([2]), array([3]))





          share|improve this answer













          The problem with your where expression occurs inside it, in your attempt to combine two conditions:



          In [210]: np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0 
          ---------------------------------------------------------------------------
          ValueError Traceback (most recent call last)
          <ipython-input-210-46c837435a31> in <module>
          ----> 1 np.sum(arr, axis=1) == 0 and np.sum(arr, axis=0) == 0

          ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
          In [211]: (np.sum(arr, axis=1) == 0) & (np.sum(arr, axis=0) == 0)
          Out[211]: array([False, False, False, False])


          You have to wrap the == test inside () so it occurs first, and you have to use & to perform element-wise and. and is a scalar operation, and does not play well with boolean arrays.



          The row and column tests are:



          In [212]: arr.sum(0)==0 
          Out[212]: array([False, False, False, True])
          In [213]: arr.sum(1)==0
          Out[213]: array([False, False, True, False])


          but you want a kind of outer or cartesian combination, not a simple element-wise combination (that would be more obvious if there were different numbers of rows and columns).



          In [218]: (arr.sum(1)==0)[:,None] & (arr.sum(0)==0) 
          Out[218]:
          array([[False, False, False, False],
          [False, False, False, False],
          [False, False, False, True],
          [False, False, False, False]])
          In [219]: np.where(_)
          Out[219]: (array([2]), array([3]))


          Or with the keepdims parameter of sum:



          In [220]: arr.sum(0, keepdims=True)==0 
          Out[220]: array([[False, False, False, True]])
          In [221]: arr.sum(1, keepdims=True)==0
          Out[221]:
          array([[False],
          [False],
          [ True],
          [False]])
          In [222]: np.where(_220 & _221) # Out[220] etc
          Out[222]: (array([2]), array([3]))






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 20:44









          hpauljhpaulj

          122k791166




          122k791166























              0














              Here is a solution using product from itertools. Creating a list of rows and columns with sums == 0 and finding the combinations between them.



              from itertools import product

              my_array = np.matrix([[3, 7, 0, 0],
              [0, 2, 0, 0],
              [0, 0, 0, 0],
              [0, 0, 1, 0]])


              a = np.argwhere(my_array.sum(axis = 1) == 0)[:,0]
              b = np.argwhere(my_array.sum(axis = 0) == 0)[:,1]

              np.array(list(product(a,b)))





              share|improve this answer



























                0














                Here is a solution using product from itertools. Creating a list of rows and columns with sums == 0 and finding the combinations between them.



                from itertools import product

                my_array = np.matrix([[3, 7, 0, 0],
                [0, 2, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 1, 0]])


                a = np.argwhere(my_array.sum(axis = 1) == 0)[:,0]
                b = np.argwhere(my_array.sum(axis = 0) == 0)[:,1]

                np.array(list(product(a,b)))





                share|improve this answer

























                  0












                  0








                  0







                  Here is a solution using product from itertools. Creating a list of rows and columns with sums == 0 and finding the combinations between them.



                  from itertools import product

                  my_array = np.matrix([[3, 7, 0, 0],
                  [0, 2, 0, 0],
                  [0, 0, 0, 0],
                  [0, 0, 1, 0]])


                  a = np.argwhere(my_array.sum(axis = 1) == 0)[:,0]
                  b = np.argwhere(my_array.sum(axis = 0) == 0)[:,1]

                  np.array(list(product(a,b)))





                  share|improve this answer













                  Here is a solution using product from itertools. Creating a list of rows and columns with sums == 0 and finding the combinations between them.



                  from itertools import product

                  my_array = np.matrix([[3, 7, 0, 0],
                  [0, 2, 0, 0],
                  [0, 0, 0, 0],
                  [0, 0, 1, 0]])


                  a = np.argwhere(my_array.sum(axis = 1) == 0)[:,0]
                  b = np.argwhere(my_array.sum(axis = 0) == 0)[:,1]

                  np.array(list(product(a,b)))






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 at 20:05









                  Christian SloperChristian Sloper

                  3,214518




                  3,214518



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327903%2ffinding-index-of-the-element-in-a-numpy-array-witout-using-for-loop%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript