Indexing numpy 2D array that wraps around











up vote
3
down vote

favorite












How do you index a numpy array that wraps around when its out of bounds?



For example, I have 3x3 array:



import numpy as np

matrix = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

##
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]]


Say I would like to index the values around index (2,4) where value 15 is located. I would like to get back the array with values:



[[9,  10, 6]
[14, 15, 11]
[4, 5, 1]]


Basically all the values around 15 was returned, assuming it wraps around










share|improve this question






















  • look at np.take
    – hpaulj
    Nov 5 at 2:21















up vote
3
down vote

favorite












How do you index a numpy array that wraps around when its out of bounds?



For example, I have 3x3 array:



import numpy as np

matrix = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

##
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]]


Say I would like to index the values around index (2,4) where value 15 is located. I would like to get back the array with values:



[[9,  10, 6]
[14, 15, 11]
[4, 5, 1]]


Basically all the values around 15 was returned, assuming it wraps around










share|improve this question






















  • look at np.take
    – hpaulj
    Nov 5 at 2:21













up vote
3
down vote

favorite









up vote
3
down vote

favorite











How do you index a numpy array that wraps around when its out of bounds?



For example, I have 3x3 array:



import numpy as np

matrix = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

##
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]]


Say I would like to index the values around index (2,4) where value 15 is located. I would like to get back the array with values:



[[9,  10, 6]
[14, 15, 11]
[4, 5, 1]]


Basically all the values around 15 was returned, assuming it wraps around










share|improve this question













How do you index a numpy array that wraps around when its out of bounds?



For example, I have 3x3 array:



import numpy as np

matrix = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

##
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]]


Say I would like to index the values around index (2,4) where value 15 is located. I would like to get back the array with values:



[[9,  10, 6]
[14, 15, 11]
[4, 5, 1]]


Basically all the values around 15 was returned, assuming it wraps around







python numpy indexing






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 5 at 2:10









user1179317

553617




553617












  • look at np.take
    – hpaulj
    Nov 5 at 2:21


















  • look at np.take
    – hpaulj
    Nov 5 at 2:21
















look at np.take
– hpaulj
Nov 5 at 2:21




look at np.take
– hpaulj
Nov 5 at 2:21












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










Here's how you can do it without padding. This can generalize easily to when you want more than just one neighbor and without the overhead of padding the array.



def get_wrapped(matrix, i, j):
m, n = matrix.shape
rows = [(i-1) % m, i, (i+1) % m]
cols = [(j-1) % n, j, (j+1) % n]
return matrix[rows][:, cols]

res = get_wrapped(matrix, 2, 4)




Let me explain what's happening here return matrix[rows][:, cols]. This is really two operations.



The first is matrix[rows] which is short hand for matrix[rows, :] which means give me the selected rows, and all columns for those rows.



Then next we do [:, cols] which means give me all the rows and the selected cols.






share|improve this answer























  • I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
    – user1179317
    Nov 5 at 2:50






  • 1




    So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
    – SilverSlash
    Nov 5 at 2:52






  • 1




    Ah right, that makes a lot of sense. Thank you for the explanation
    – user1179317
    Nov 5 at 2:59






  • 1




    Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
    – hpaulj
    Nov 5 at 6:05


















up vote
4
down vote













A fairly standard idiom to find the neighboring elements in a numpy array is arr[x-1:x+2, y-1:y+2]. However, since you want to wrap, you can pad your array using wrap mode, and offset your x and y coordinates to account for this padding.



This answer assumes that you want the neighbors of the first occurence of your desired element.





First, find the indices of your element, and offset to account for padding:



x, y = np.unravel_index((m==15).argmax(), m.shape)
x += 1; y += 1


Now pad, and index your array to get your neighbors:



t = np.pad(m, 1, mode='wrap')    
out = t[x-1:x+2, y-1:y+2]




array([[ 9, 10,  6],
[14, 15, 11],
[ 4, 5, 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',
    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%2f53147439%2findexing-numpy-2d-array-that-wraps-around%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Here's how you can do it without padding. This can generalize easily to when you want more than just one neighbor and without the overhead of padding the array.



    def get_wrapped(matrix, i, j):
    m, n = matrix.shape
    rows = [(i-1) % m, i, (i+1) % m]
    cols = [(j-1) % n, j, (j+1) % n]
    return matrix[rows][:, cols]

    res = get_wrapped(matrix, 2, 4)




    Let me explain what's happening here return matrix[rows][:, cols]. This is really two operations.



    The first is matrix[rows] which is short hand for matrix[rows, :] which means give me the selected rows, and all columns for those rows.



    Then next we do [:, cols] which means give me all the rows and the selected cols.






    share|improve this answer























    • I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
      – user1179317
      Nov 5 at 2:50






    • 1




      So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
      – SilverSlash
      Nov 5 at 2:52






    • 1




      Ah right, that makes a lot of sense. Thank you for the explanation
      – user1179317
      Nov 5 at 2:59






    • 1




      Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
      – hpaulj
      Nov 5 at 6:05















    up vote
    1
    down vote



    accepted










    Here's how you can do it without padding. This can generalize easily to when you want more than just one neighbor and without the overhead of padding the array.



    def get_wrapped(matrix, i, j):
    m, n = matrix.shape
    rows = [(i-1) % m, i, (i+1) % m]
    cols = [(j-1) % n, j, (j+1) % n]
    return matrix[rows][:, cols]

    res = get_wrapped(matrix, 2, 4)




    Let me explain what's happening here return matrix[rows][:, cols]. This is really two operations.



    The first is matrix[rows] which is short hand for matrix[rows, :] which means give me the selected rows, and all columns for those rows.



    Then next we do [:, cols] which means give me all the rows and the selected cols.






    share|improve this answer























    • I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
      – user1179317
      Nov 5 at 2:50






    • 1




      So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
      – SilverSlash
      Nov 5 at 2:52






    • 1




      Ah right, that makes a lot of sense. Thank you for the explanation
      – user1179317
      Nov 5 at 2:59






    • 1




      Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
      – hpaulj
      Nov 5 at 6:05













    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    Here's how you can do it without padding. This can generalize easily to when you want more than just one neighbor and without the overhead of padding the array.



    def get_wrapped(matrix, i, j):
    m, n = matrix.shape
    rows = [(i-1) % m, i, (i+1) % m]
    cols = [(j-1) % n, j, (j+1) % n]
    return matrix[rows][:, cols]

    res = get_wrapped(matrix, 2, 4)




    Let me explain what's happening here return matrix[rows][:, cols]. This is really two operations.



    The first is matrix[rows] which is short hand for matrix[rows, :] which means give me the selected rows, and all columns for those rows.



    Then next we do [:, cols] which means give me all the rows and the selected cols.






    share|improve this answer














    Here's how you can do it without padding. This can generalize easily to when you want more than just one neighbor and without the overhead of padding the array.



    def get_wrapped(matrix, i, j):
    m, n = matrix.shape
    rows = [(i-1) % m, i, (i+1) % m]
    cols = [(j-1) % n, j, (j+1) % n]
    return matrix[rows][:, cols]

    res = get_wrapped(matrix, 2, 4)




    Let me explain what's happening here return matrix[rows][:, cols]. This is really two operations.



    The first is matrix[rows] which is short hand for matrix[rows, :] which means give me the selected rows, and all columns for those rows.



    Then next we do [:, cols] which means give me all the rows and the selected cols.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 5 at 2:55

























    answered Nov 5 at 2:37









    SilverSlash

    507212




    507212












    • I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
      – user1179317
      Nov 5 at 2:50






    • 1




      So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
      – SilverSlash
      Nov 5 at 2:52






    • 1




      Ah right, that makes a lot of sense. Thank you for the explanation
      – user1179317
      Nov 5 at 2:59






    • 1




      Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
      – hpaulj
      Nov 5 at 6:05


















    • I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
      – user1179317
      Nov 5 at 2:50






    • 1




      So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
      – SilverSlash
      Nov 5 at 2:52






    • 1




      Ah right, that makes a lot of sense. Thank you for the explanation
      – user1179317
      Nov 5 at 2:59






    • 1




      Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
      – hpaulj
      Nov 5 at 6:05
















    I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
    – user1179317
    Nov 5 at 2:50




    I see, this is actually very adaptable where if i want 2 neighbors i can just add 2 elements in the row and col list with a -2 and a +2. The only thing Im a little confuse about is whats the : for matrix[rows][:, cols]. I would think its just for matrix[rows][cols] but obviously that doesnt work.
    – user1179317
    Nov 5 at 2:50




    1




    1




    So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
    – SilverSlash
    Nov 5 at 2:52




    So in numpy you can index into matrices using matrix[row, col] instead of pythons list[row][col]. So what that is doing is really two separate indexings a = matrix[rows] and b = a[:, cols]. The : just means all.
    – SilverSlash
    Nov 5 at 2:52




    1




    1




    Ah right, that makes a lot of sense. Thank you for the explanation
    – user1179317
    Nov 5 at 2:59




    Ah right, that makes a lot of sense. Thank you for the explanation
    – user1179317
    Nov 5 at 2:59




    1




    1




    Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
    – hpaulj
    Nov 5 at 6:05




    Each '` is evaluated (by the Python interpreter) individually. matrix[rows] is done, then [cols] on the result. So you have to pay attention to the intermediate result. In [rows, cols] numpy handles both parts together.
    – hpaulj
    Nov 5 at 6:05












    up vote
    4
    down vote













    A fairly standard idiom to find the neighboring elements in a numpy array is arr[x-1:x+2, y-1:y+2]. However, since you want to wrap, you can pad your array using wrap mode, and offset your x and y coordinates to account for this padding.



    This answer assumes that you want the neighbors of the first occurence of your desired element.





    First, find the indices of your element, and offset to account for padding:



    x, y = np.unravel_index((m==15).argmax(), m.shape)
    x += 1; y += 1


    Now pad, and index your array to get your neighbors:



    t = np.pad(m, 1, mode='wrap')    
    out = t[x-1:x+2, y-1:y+2]




    array([[ 9, 10,  6],
    [14, 15, 11],
    [ 4, 5, 1]])





    share|improve this answer



























      up vote
      4
      down vote













      A fairly standard idiom to find the neighboring elements in a numpy array is arr[x-1:x+2, y-1:y+2]. However, since you want to wrap, you can pad your array using wrap mode, and offset your x and y coordinates to account for this padding.



      This answer assumes that you want the neighbors of the first occurence of your desired element.





      First, find the indices of your element, and offset to account for padding:



      x, y = np.unravel_index((m==15).argmax(), m.shape)
      x += 1; y += 1


      Now pad, and index your array to get your neighbors:



      t = np.pad(m, 1, mode='wrap')    
      out = t[x-1:x+2, y-1:y+2]




      array([[ 9, 10,  6],
      [14, 15, 11],
      [ 4, 5, 1]])





      share|improve this answer

























        up vote
        4
        down vote










        up vote
        4
        down vote









        A fairly standard idiom to find the neighboring elements in a numpy array is arr[x-1:x+2, y-1:y+2]. However, since you want to wrap, you can pad your array using wrap mode, and offset your x and y coordinates to account for this padding.



        This answer assumes that you want the neighbors of the first occurence of your desired element.





        First, find the indices of your element, and offset to account for padding:



        x, y = np.unravel_index((m==15).argmax(), m.shape)
        x += 1; y += 1


        Now pad, and index your array to get your neighbors:



        t = np.pad(m, 1, mode='wrap')    
        out = t[x-1:x+2, y-1:y+2]




        array([[ 9, 10,  6],
        [14, 15, 11],
        [ 4, 5, 1]])





        share|improve this answer














        A fairly standard idiom to find the neighboring elements in a numpy array is arr[x-1:x+2, y-1:y+2]. However, since you want to wrap, you can pad your array using wrap mode, and offset your x and y coordinates to account for this padding.



        This answer assumes that you want the neighbors of the first occurence of your desired element.





        First, find the indices of your element, and offset to account for padding:



        x, y = np.unravel_index((m==15).argmax(), m.shape)
        x += 1; y += 1


        Now pad, and index your array to get your neighbors:



        t = np.pad(m, 1, mode='wrap')    
        out = t[x-1:x+2, y-1:y+2]




        array([[ 9, 10,  6],
        [14, 15, 11],
        [ 4, 5, 1]])






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 5 at 2:30

























        answered Nov 5 at 2:25









        user3483203

        28.2k72351




        28.2k72351






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147439%2findexing-numpy-2d-array-that-wraps-around%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings