How to efficiently subtract values from each column with numpyHow to randomly select an item from a list?How to subtract a day from a date?How do I sort a dictionary by value?How do I determine whether an array contains a particular value in Java?Peak detection in a 2D arrayHow to access the ith column of a NumPy multidimensional array?How to access environment variable values?How do I remove a particular element from an array in JavaScript?Delete column from pandas DataFrameSelect rows from a DataFrame based on values in a column in pandas

Count rook moves 1D

Replacing values of raster in R to produce landuse-like raster map?

In-universe, why does Doc Brown program the time machine to go to 1955?

How did Gollum know Sauron was gathering the Haradrim to make war?

Case Studies and Real Problems for Teaching Optimization and Modelling

What would a biological creature need in order to see the future?

Is mathematics truth?

Given a specific computer system, is it possible to estimate the actual precise run time of a piece of Assembly code

If p-value is exactly 1 (1.0000000), what are the confidence interval limits?

What happens if I double Meddling Mage's 'enter the battlefield' trigger?

Is it rude to ask my opponent to resign an online game when they have a lost endgame?

Is torque as fundamental a concept as force?

Tiny image scraper for xkcd.com

Any possible ways to stop co-workers coming in really early?

'Hard work never hurt anyone' Why not 'hurts'?

What did Boris Johnson mean when he said "extra 34 billion going into the NHS"

A rather curious equality: is this true?

Real-world issues with using an alias

Deleting millions of records on SQL Server 14.0

Can I take a soft suitcase on Qatar Airways?

Do I need to get a noble in order to win Splendor?

Do index funds really have double-digit percents annual return rates?

What is the most likely cause of short, quick, and useless reviews?

Queries and updates extremely slow after IndexOptimize



How to efficiently subtract values from each column with numpy


How to randomly select an item from a list?How to subtract a day from a date?How do I sort a dictionary by value?How do I determine whether an array contains a particular value in Java?Peak detection in a 2D arrayHow to access the ith column of a NumPy multidimensional array?How to access environment variable values?How do I remove a particular element from an array in JavaScript?Delete column from pandas DataFrameSelect rows from a DataFrame based on values in a column in pandas






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a 2D array of shape (50,50). I need to subtract a value from each column of this array skipping the first), which is calculated based on the index of the column. For example, using a for loop it would look something like this:



for idx in range(1, A[0, :].shape[0]):
A[0, idx] -= idx * (...) # simple calculations with idx


Now, of course this works fine, but it's very slow and performance is critical for my application. I've tried computing the values to be subtracted using np.fromfunction() and then subtracting it from the original array, but results are different than those obtained by the for loop iteractive subtraction:



 func = lambda i, j: j * (...) #some simple calculations
subtraction_matrix = np.fromfunction(np.vectorize(func), (1,50))

A[0, 1:] -= subtraction_matrix


What am I doing wrong? Or is there some other method that would be better? Any help is appreciated!










share|improve this question
























  • Could you please give an example of input/output?

    – iz_
    Mar 28 at 2:55

















0















I have a 2D array of shape (50,50). I need to subtract a value from each column of this array skipping the first), which is calculated based on the index of the column. For example, using a for loop it would look something like this:



for idx in range(1, A[0, :].shape[0]):
A[0, idx] -= idx * (...) # simple calculations with idx


Now, of course this works fine, but it's very slow and performance is critical for my application. I've tried computing the values to be subtracted using np.fromfunction() and then subtracting it from the original array, but results are different than those obtained by the for loop iteractive subtraction:



 func = lambda i, j: j * (...) #some simple calculations
subtraction_matrix = np.fromfunction(np.vectorize(func), (1,50))

A[0, 1:] -= subtraction_matrix


What am I doing wrong? Or is there some other method that would be better? Any help is appreciated!










share|improve this question
























  • Could you please give an example of input/output?

    – iz_
    Mar 28 at 2:55













0












0








0








I have a 2D array of shape (50,50). I need to subtract a value from each column of this array skipping the first), which is calculated based on the index of the column. For example, using a for loop it would look something like this:



for idx in range(1, A[0, :].shape[0]):
A[0, idx] -= idx * (...) # simple calculations with idx


Now, of course this works fine, but it's very slow and performance is critical for my application. I've tried computing the values to be subtracted using np.fromfunction() and then subtracting it from the original array, but results are different than those obtained by the for loop iteractive subtraction:



 func = lambda i, j: j * (...) #some simple calculations
subtraction_matrix = np.fromfunction(np.vectorize(func), (1,50))

A[0, 1:] -= subtraction_matrix


What am I doing wrong? Or is there some other method that would be better? Any help is appreciated!










share|improve this question














I have a 2D array of shape (50,50). I need to subtract a value from each column of this array skipping the first), which is calculated based on the index of the column. For example, using a for loop it would look something like this:



for idx in range(1, A[0, :].shape[0]):
A[0, idx] -= idx * (...) # simple calculations with idx


Now, of course this works fine, but it's very slow and performance is critical for my application. I've tried computing the values to be subtracted using np.fromfunction() and then subtracting it from the original array, but results are different than those obtained by the for loop iteractive subtraction:



 func = lambda i, j: j * (...) #some simple calculations
subtraction_matrix = np.fromfunction(np.vectorize(func), (1,50))

A[0, 1:] -= subtraction_matrix


What am I doing wrong? Or is there some other method that would be better? Any help is appreciated!







python arrays numpy matrix






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 2:51









Gabriel LefundesGabriel Lefundes

589 bronze badges




589 bronze badges















  • Could you please give an example of input/output?

    – iz_
    Mar 28 at 2:55

















  • Could you please give an example of input/output?

    – iz_
    Mar 28 at 2:55
















Could you please give an example of input/output?

– iz_
Mar 28 at 2:55





Could you please give an example of input/output?

– iz_
Mar 28 at 2:55












1 Answer
1






active

oldest

votes


















0















All your code snippets indicate that you require the subtraction to happen only in the first row of A (though you've not explicitly mentioned that). So, I'm proceeding with that understanding.



Referring to your use of from_function(), you can use the subtraction_matrix as below:



A[0,1:] -= subtraction_matrix[1:]


Testing it out (assuming shape (5,5) instead of (50,50)):



import numpy as np

A = np.arange(25).reshape(5,5)
print (A)

func = lambda j: j * 10 #some simple calculations
subtraction_matrix = np.fromfunction(np.vectorize(func), (5,), dtype=A.dtype)

A[0,1:] -= subtraction_matrix[1:]
print (A)


Output:



[[ 0 1 2 3 4] # print(A), before subtraction
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]

[[ 0 -9 -18 -27 -36] # print(A), after subtraction
[ 5 6 7 8 9]
[ 10 11 12 13 14]
[ 15 16 17 18 19]
[ 20 21 22 23 24]]



If you want the subtraction to happen in all the rows of A, you just need to use the line A[:,1:] -= subtraction_matrix[1:], instead of the line A[0,1:] -= subtraction_matrix[1:]






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%2f55389481%2fhow-to-efficiently-subtract-values-from-each-column-with-numpy%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









    0















    All your code snippets indicate that you require the subtraction to happen only in the first row of A (though you've not explicitly mentioned that). So, I'm proceeding with that understanding.



    Referring to your use of from_function(), you can use the subtraction_matrix as below:



    A[0,1:] -= subtraction_matrix[1:]


    Testing it out (assuming shape (5,5) instead of (50,50)):



    import numpy as np

    A = np.arange(25).reshape(5,5)
    print (A)

    func = lambda j: j * 10 #some simple calculations
    subtraction_matrix = np.fromfunction(np.vectorize(func), (5,), dtype=A.dtype)

    A[0,1:] -= subtraction_matrix[1:]
    print (A)


    Output:



    [[ 0 1 2 3 4] # print(A), before subtraction
    [ 5 6 7 8 9]
    [10 11 12 13 14]
    [15 16 17 18 19]
    [20 21 22 23 24]]

    [[ 0 -9 -18 -27 -36] # print(A), after subtraction
    [ 5 6 7 8 9]
    [ 10 11 12 13 14]
    [ 15 16 17 18 19]
    [ 20 21 22 23 24]]



    If you want the subtraction to happen in all the rows of A, you just need to use the line A[:,1:] -= subtraction_matrix[1:], instead of the line A[0,1:] -= subtraction_matrix[1:]






    share|improve this answer































      0















      All your code snippets indicate that you require the subtraction to happen only in the first row of A (though you've not explicitly mentioned that). So, I'm proceeding with that understanding.



      Referring to your use of from_function(), you can use the subtraction_matrix as below:



      A[0,1:] -= subtraction_matrix[1:]


      Testing it out (assuming shape (5,5) instead of (50,50)):



      import numpy as np

      A = np.arange(25).reshape(5,5)
      print (A)

      func = lambda j: j * 10 #some simple calculations
      subtraction_matrix = np.fromfunction(np.vectorize(func), (5,), dtype=A.dtype)

      A[0,1:] -= subtraction_matrix[1:]
      print (A)


      Output:



      [[ 0 1 2 3 4] # print(A), before subtraction
      [ 5 6 7 8 9]
      [10 11 12 13 14]
      [15 16 17 18 19]
      [20 21 22 23 24]]

      [[ 0 -9 -18 -27 -36] # print(A), after subtraction
      [ 5 6 7 8 9]
      [ 10 11 12 13 14]
      [ 15 16 17 18 19]
      [ 20 21 22 23 24]]



      If you want the subtraction to happen in all the rows of A, you just need to use the line A[:,1:] -= subtraction_matrix[1:], instead of the line A[0,1:] -= subtraction_matrix[1:]






      share|improve this answer





























        0














        0










        0









        All your code snippets indicate that you require the subtraction to happen only in the first row of A (though you've not explicitly mentioned that). So, I'm proceeding with that understanding.



        Referring to your use of from_function(), you can use the subtraction_matrix as below:



        A[0,1:] -= subtraction_matrix[1:]


        Testing it out (assuming shape (5,5) instead of (50,50)):



        import numpy as np

        A = np.arange(25).reshape(5,5)
        print (A)

        func = lambda j: j * 10 #some simple calculations
        subtraction_matrix = np.fromfunction(np.vectorize(func), (5,), dtype=A.dtype)

        A[0,1:] -= subtraction_matrix[1:]
        print (A)


        Output:



        [[ 0 1 2 3 4] # print(A), before subtraction
        [ 5 6 7 8 9]
        [10 11 12 13 14]
        [15 16 17 18 19]
        [20 21 22 23 24]]

        [[ 0 -9 -18 -27 -36] # print(A), after subtraction
        [ 5 6 7 8 9]
        [ 10 11 12 13 14]
        [ 15 16 17 18 19]
        [ 20 21 22 23 24]]



        If you want the subtraction to happen in all the rows of A, you just need to use the line A[:,1:] -= subtraction_matrix[1:], instead of the line A[0,1:] -= subtraction_matrix[1:]






        share|improve this answer















        All your code snippets indicate that you require the subtraction to happen only in the first row of A (though you've not explicitly mentioned that). So, I'm proceeding with that understanding.



        Referring to your use of from_function(), you can use the subtraction_matrix as below:



        A[0,1:] -= subtraction_matrix[1:]


        Testing it out (assuming shape (5,5) instead of (50,50)):



        import numpy as np

        A = np.arange(25).reshape(5,5)
        print (A)

        func = lambda j: j * 10 #some simple calculations
        subtraction_matrix = np.fromfunction(np.vectorize(func), (5,), dtype=A.dtype)

        A[0,1:] -= subtraction_matrix[1:]
        print (A)


        Output:



        [[ 0 1 2 3 4] # print(A), before subtraction
        [ 5 6 7 8 9]
        [10 11 12 13 14]
        [15 16 17 18 19]
        [20 21 22 23 24]]

        [[ 0 -9 -18 -27 -36] # print(A), after subtraction
        [ 5 6 7 8 9]
        [ 10 11 12 13 14]
        [ 15 16 17 18 19]
        [ 20 21 22 23 24]]



        If you want the subtraction to happen in all the rows of A, you just need to use the line A[:,1:] -= subtraction_matrix[1:], instead of the line A[0,1:] -= subtraction_matrix[1:]







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 28 at 3:38

























        answered Mar 28 at 3:25









        fountainheadfountainhead

        1,4003 silver badges13 bronze badges




        1,4003 silver badges13 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            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%2f55389481%2fhow-to-efficiently-subtract-values-from-each-column-with-numpy%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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해