Lee Cottrell
Lee Cottrell

Reputation: 35

Which of these two numpy slices are better to use?

I am learning Python through an online course. We were asked to slice a 6x6 numpy array and get the diagonal. As a group we developed two methods, shown below. Is one better than the other?

import numpy as n
six = n.arange(1, 73, 2)
six.reshape(6,6)

Solutions found

six[::7]
six.reshape(36)[::7]

My answers both return array([ 1, 15, 29, 43, 57, 71])

I like the first, my partner likes the second. Any help would be very appreciated.

Thank you!

Upvotes: 0

Views: 57

Answers (2)

AGN Gazer
AGN Gazer

Reputation: 8378

six.reshape(6,6)

does not modify six itself: it just returns a new 2D array but leaves six unchanged. So, your two methods are in effect one and the same method.

You can verify this by doing:

>>> six = np.arange(1, 73, 2)
>>> six.reshape(6,6)
>>> print(six)

You will get a 1D array like:

[ 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71]

Therefore, I declare that the answer that does not use the unnecessary reshape call (assuming six is a flat array created with np.arange(1, 73, 2)) is the best answer :)

Upvotes: 2

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Let's fix your code a bit first so it does what you intend:

six = np.arange(1, 73, 2).reshape(6, 6)

Now comparing your approach:

>>> six[::7]
array([[ 1,  3,  5,  7,  9, 11]])

To your partner's:

>>> six.reshape(36)[::7]
array([ 1, 15, 29, 43, 57, 71])

Upvotes: 1

Related Questions