Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing arrays with lists

So, I create a numpy array:

a = np.arange(25).reshape(5,5)

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

A conventional slice a[1:3,1:3] returns

array([[ 6, 7], [11, 12]])

as does using a list in the second a[1:3,[1,2]]

array([[ 6, 7], [11, 12]])

However, a[[1,2],[1,2]] returns

array([ 6, 12])

Obviously I am not understanding something here. That said, slicing with a list might on occasion be very useful.

Cheers,

keng

like image 672
keng Avatar asked Jan 14 '20 19:01

keng


People also ask

Can we do slicing in list?

As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign. In python terminology, this is because lists are mutable objects, while strings are immutable.

Can you slice a list in Python?

In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges.

How do you splice a list?

The splice() function can be used in three ways: Transfer all the elements of list x into another list at some position. Transfer only the element pointed by i from list x into the list at some position. Transfers the range [first, last) from list x into another list at some position.

What is the critical difference between slicing lists and arrays?

when we take a slice of an array, the returned array is a view of the original array — we have ultimately accessed the same data in a different order. Whereas, when we slice a list it will return a completely new list.


Video Answer


1 Answers

You observed effect of so-called Advanced Indexing. Let consider example from link:

import numpy as np
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x)
[[1 2]
 [3 4]
 [5 6]]
print(x[[0, 1, 2], [0, 1, 0]])  # [1 4 5]

You might think about this as providing lists of (Cartesian) coordinates of grid, as

print(x[0,1])  # 1
print(x[1,1])  # 4
print(x[2,0])  # 5
like image 151
Daweo Avatar answered Nov 14 '22 22:11

Daweo