numpy add along first axis











up vote
3
down vote

favorite












I would like to add two arrays with different dimensions by simply performing an identical addition along the first axis.



A non-vectorized solution:



x = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,0],[1,2]],[[3,4],[5,6],[7,8]],[[9,0],[1,2],[3,4]]]) #shape (4,3,2)
y = np.array([[1,2],[3,4],[5,6]]) #shape (3,2)

ans = np.empty(x.shape)
for i in range(x.shape[0]):
ans[i] = x[i] + y

print(ans) #shape (4,3,2)


How can I make this broadcast appropriately?










share|improve this question




























    up vote
    3
    down vote

    favorite












    I would like to add two arrays with different dimensions by simply performing an identical addition along the first axis.



    A non-vectorized solution:



    x = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,0],[1,2]],[[3,4],[5,6],[7,8]],[[9,0],[1,2],[3,4]]]) #shape (4,3,2)
    y = np.array([[1,2],[3,4],[5,6]]) #shape (3,2)

    ans = np.empty(x.shape)
    for i in range(x.shape[0]):
    ans[i] = x[i] + y

    print(ans) #shape (4,3,2)


    How can I make this broadcast appropriately?










    share|improve this question


























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      I would like to add two arrays with different dimensions by simply performing an identical addition along the first axis.



      A non-vectorized solution:



      x = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,0],[1,2]],[[3,4],[5,6],[7,8]],[[9,0],[1,2],[3,4]]]) #shape (4,3,2)
      y = np.array([[1,2],[3,4],[5,6]]) #shape (3,2)

      ans = np.empty(x.shape)
      for i in range(x.shape[0]):
      ans[i] = x[i] + y

      print(ans) #shape (4,3,2)


      How can I make this broadcast appropriately?










      share|improve this question















      I would like to add two arrays with different dimensions by simply performing an identical addition along the first axis.



      A non-vectorized solution:



      x = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,0],[1,2]],[[3,4],[5,6],[7,8]],[[9,0],[1,2],[3,4]]]) #shape (4,3,2)
      y = np.array([[1,2],[3,4],[5,6]]) #shape (3,2)

      ans = np.empty(x.shape)
      for i in range(x.shape[0]):
      ans[i] = x[i] + y

      print(ans) #shape (4,3,2)


      How can I make this broadcast appropriately?







      python numpy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 22:02

























      asked Nov 8 at 21:54









      Scott

      1,720823




      1,720823
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          Due to broadcasting [numpy-doc], you can simply use:



          x + y


          So here we calculate the element at index i,j,k as:



          xijk+yjk



          this gives:



          >>> x + y
          array([[[ 2, 4],
          [ 6, 8],
          [10, 12]],

          [[ 8, 10],
          [12, 4],
          [ 6, 8]],

          [[ 4, 6],
          [ 8, 10],
          [12, 14]],

          [[10, 2],
          [ 4, 6],
          [ 8, 10]]])
          >>> (x + y).shape
          (4, 3, 2)


          If you add two arrays together such that the first array has for example three dimensions, and the second two dimensions, and the last two dimensions of the first left array equal the dimensions of the right array, the the array on the right side is "broacasted". It means that it is treated as a three dimensional array, where each subarray equals the array on the right side.



          You can als "introduce" extra dimensions for y at arbitrary positions like in this answer to "broadcast" a specific dimension.






          share|improve this answer























          • (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
            – Scott
            Nov 8 at 22:02










          • @Scott: normally it also works for more dimensions, it aligns typically to the right.
            – Willem Van Onsem
            Nov 8 at 22:02










          • Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
            – Scott
            Nov 8 at 22:07










          • @Scott: well you could transpose, etc. and then do the calculations.
            – Willem Van Onsem
            Nov 8 at 22:09











          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',
          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%2f53216750%2fnumpy-add-along-first-axis%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote



          accepted










          Due to broadcasting [numpy-doc], you can simply use:



          x + y


          So here we calculate the element at index i,j,k as:



          xijk+yjk



          this gives:



          >>> x + y
          array([[[ 2, 4],
          [ 6, 8],
          [10, 12]],

          [[ 8, 10],
          [12, 4],
          [ 6, 8]],

          [[ 4, 6],
          [ 8, 10],
          [12, 14]],

          [[10, 2],
          [ 4, 6],
          [ 8, 10]]])
          >>> (x + y).shape
          (4, 3, 2)


          If you add two arrays together such that the first array has for example three dimensions, and the second two dimensions, and the last two dimensions of the first left array equal the dimensions of the right array, the the array on the right side is "broacasted". It means that it is treated as a three dimensional array, where each subarray equals the array on the right side.



          You can als "introduce" extra dimensions for y at arbitrary positions like in this answer to "broadcast" a specific dimension.






          share|improve this answer























          • (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
            – Scott
            Nov 8 at 22:02










          • @Scott: normally it also works for more dimensions, it aligns typically to the right.
            – Willem Van Onsem
            Nov 8 at 22:02










          • Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
            – Scott
            Nov 8 at 22:07










          • @Scott: well you could transpose, etc. and then do the calculations.
            – Willem Van Onsem
            Nov 8 at 22:09















          up vote
          3
          down vote



          accepted










          Due to broadcasting [numpy-doc], you can simply use:



          x + y


          So here we calculate the element at index i,j,k as:



          xijk+yjk



          this gives:



          >>> x + y
          array([[[ 2, 4],
          [ 6, 8],
          [10, 12]],

          [[ 8, 10],
          [12, 4],
          [ 6, 8]],

          [[ 4, 6],
          [ 8, 10],
          [12, 14]],

          [[10, 2],
          [ 4, 6],
          [ 8, 10]]])
          >>> (x + y).shape
          (4, 3, 2)


          If you add two arrays together such that the first array has for example three dimensions, and the second two dimensions, and the last two dimensions of the first left array equal the dimensions of the right array, the the array on the right side is "broacasted". It means that it is treated as a three dimensional array, where each subarray equals the array on the right side.



          You can als "introduce" extra dimensions for y at arbitrary positions like in this answer to "broadcast" a specific dimension.






          share|improve this answer























          • (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
            – Scott
            Nov 8 at 22:02










          • @Scott: normally it also works for more dimensions, it aligns typically to the right.
            – Willem Van Onsem
            Nov 8 at 22:02










          • Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
            – Scott
            Nov 8 at 22:07










          • @Scott: well you could transpose, etc. and then do the calculations.
            – Willem Van Onsem
            Nov 8 at 22:09













          up vote
          3
          down vote



          accepted







          up vote
          3
          down vote



          accepted






          Due to broadcasting [numpy-doc], you can simply use:



          x + y


          So here we calculate the element at index i,j,k as:



          xijk+yjk



          this gives:



          >>> x + y
          array([[[ 2, 4],
          [ 6, 8],
          [10, 12]],

          [[ 8, 10],
          [12, 4],
          [ 6, 8]],

          [[ 4, 6],
          [ 8, 10],
          [12, 14]],

          [[10, 2],
          [ 4, 6],
          [ 8, 10]]])
          >>> (x + y).shape
          (4, 3, 2)


          If you add two arrays together such that the first array has for example three dimensions, and the second two dimensions, and the last two dimensions of the first left array equal the dimensions of the right array, the the array on the right side is "broacasted". It means that it is treated as a three dimensional array, where each subarray equals the array on the right side.



          You can als "introduce" extra dimensions for y at arbitrary positions like in this answer to "broadcast" a specific dimension.






          share|improve this answer














          Due to broadcasting [numpy-doc], you can simply use:



          x + y


          So here we calculate the element at index i,j,k as:



          xijk+yjk



          this gives:



          >>> x + y
          array([[[ 2, 4],
          [ 6, 8],
          [10, 12]],

          [[ 8, 10],
          [12, 4],
          [ 6, 8]],

          [[ 4, 6],
          [ 8, 10],
          [12, 14]],

          [[10, 2],
          [ 4, 6],
          [ 8, 10]]])
          >>> (x + y).shape
          (4, 3, 2)


          If you add two arrays together such that the first array has for example three dimensions, and the second two dimensions, and the last two dimensions of the first left array equal the dimensions of the right array, the the array on the right side is "broacasted". It means that it is treated as a three dimensional array, where each subarray equals the array on the right side.



          You can als "introduce" extra dimensions for y at arbitrary positions like in this answer to "broadcast" a specific dimension.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 8 at 22:29

























          answered Nov 8 at 21:56









          Willem Van Onsem

          141k16132225




          141k16132225












          • (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
            – Scott
            Nov 8 at 22:02










          • @Scott: normally it also works for more dimensions, it aligns typically to the right.
            – Willem Van Onsem
            Nov 8 at 22:02










          • Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
            – Scott
            Nov 8 at 22:07










          • @Scott: well you could transpose, etc. and then do the calculations.
            – Willem Van Onsem
            Nov 8 at 22:09


















          • (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
            – Scott
            Nov 8 at 22:02










          • @Scott: normally it also works for more dimensions, it aligns typically to the right.
            – Willem Van Onsem
            Nov 8 at 22:02










          • Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
            – Scott
            Nov 8 at 22:07










          • @Scott: well you could transpose, etc. and then do the calculations.
            – Willem Van Onsem
            Nov 8 at 22:09
















          (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
          – Scott
          Nov 8 at 22:02




          (sigh)... My example was a poor illustration of the use-case "for one or more axes". I will accept this answer, edit the question to reflect this answer and post a better example in a new question.
          – Scott
          Nov 8 at 22:02












          @Scott: normally it also works for more dimensions, it aligns typically to the right.
          – Willem Van Onsem
          Nov 8 at 22:02




          @Scott: normally it also works for more dimensions, it aligns typically to the right.
          – Willem Van Onsem
          Nov 8 at 22:02












          Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
          – Scott
          Nov 8 at 22:07




          Ahhhhh.... So, for example, rolling my axes to the appropriate locations and then adding would do the trick?
          – Scott
          Nov 8 at 22:07












          @Scott: well you could transpose, etc. and then do the calculations.
          – Willem Van Onsem
          Nov 8 at 22:09




          @Scott: well you could transpose, etc. and then do the calculations.
          – Willem Van Onsem
          Nov 8 at 22:09


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53216750%2fnumpy-add-along-first-axis%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







          這個網誌中的熱門文章

          Academy of Television Arts & Sciences

          L'Équipe

          1995 France bombings