1

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,]

wowzer
  • 25
  • 5

2 Answers2

0
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]

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • I'm not sure if A1[:2] is considered as slicing... It is my thinking that anything with colon within square brackets is considered slicing. – wowzer Sep 25 '22 at 20:39
0

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]])
MagnusO_O
  • 1,202
  • 4
  • 13
  • 19