Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this slicing example doesn't work in NumPy the same way it works with standard lists?

Why this slicing example doesn't give the same results as standard lists? It works like if it first evaluates an[:2] = bn[:2] and then bn[:2] = an[:2].

import numpy as np

l1 = [1, 2, 3]
l2 = [4, 5, 6]

a = list(l1)
b = list(l2)

an = np.array(a)
bn = np.array(b)

print(a, b)
a[:2], b[:2] = b[:2], a[:2]
print(a, b)

print(an, bn)
an[:2], bn[:2] = bn[:2], an[:2]
print(an, bn)

Output:

--------------------
[1, 2, 3] [4, 5, 6]
[4, 5, 3] [1, 2, 6]
--------------------
[1 2 3] [4 5 6]
[4 5 3] [4 5 6]
--------------------

If I do it like this - everything works:

dummy = an[:2]
an[:2] = bn[:2]
bn[:2] = dummy
like image 654
userqwerty1 Avatar asked Mar 03 '16 21:03

userqwerty1


People also ask

How does NumPy array slicing work?

Slicing arrays Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .

Is NumPy a standard Python library?

It is a third-party library (i.e. it is not part of Python's standard library) that facilitates numerical computing in Python by providing users with a versatile N-dimensional array object for storing data, and powerful mathematical functions for operating on those arrays of numbers.

Can NumPy hold different data types?

Data Types in NumPyNumPy has some extra data types, and refer to data types with one character, like i for integers, u for unsigned integers etc. Below is a list of all data types in NumPy and the characters used to represent them.

How does slicing work Python?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.


1 Answers

For lists a[:2] is a copy of the list with the first two elements, for numpy arrays this is only a reference. You need to make a copy, explicitly:

an[:2], bn[:2] = bn[:2].copy(), an[:2].copy()
like image 164
Daniel Avatar answered Oct 07 '22 03:10

Daniel