Home > front end >  How to retrieve elements from an array without slicing?
How to retrieve elements from an array without slicing?

Time:09-26

Say I have an array, A1. B1 is another array storing the last two rows of A1. I need to retrieve the first two rows of A1 without slicing as another array (C1). Logically, I'm thinking something like A1 (the whole array) - B1 (the last two rows) = C1 (the first two rows), but I don't know if Python does anything like that. How do I get elements from an array without slicing? Appreciate your help!

A1 = np.array([ [1, 4, 6, 8],[2, 5, 7, 10],[3, 6, 9, 13],[11, 12, 16, 0]]) B1 = A1[2:4,]

CodePudding user response:

Instead of 'subtracting' the two arrays you could delete the last two rows:

C1 = np.delete(A1, (2,3), axis=0)
array([[ 1,  4,  6,  8],
       [ 2,  5,  7, 10]])

CodePudding user response:

def first_2_rows_of_A1():
    for i,row in enumerate(A1):
        yield row
        if i => 1:
           break

first_2_rows = list(first_2_rows_of_A1())

I guess that does what you want... but I don't understand why you wouldn't just get the first two rows as A1[:2]

  • Related