1

technically what is the difference between

import numpy as np
a = np.random.random((100,3))
b = numpy.empty((100))

# what the difference between
b = a[:,0]
# and
b[:] = a[:,0]

The reason I am asking that I am reading b with a fortran compiled function and the slicing in b is making all the difference. This has something to do with the column and row reading style between C and fortran. In default numpy convention is the C one.

1 Answer 1

3

The main difference is that

b = a[:,0]

creates a view onto a's data, whereas

b[:] = a[:,0]

makes a copy of the data.

The former uses the same memory layout as a, whereas the latter preserves the memory layout of the original b. In particular this means that in the latter case all the data gets compacted into consecutive memory locations:

In [29]: b = numpy.empty((100))

In [30]: b = a[:,0]

In [31]: b.strides
Out[31]: (24,)



In [32]: b = numpy.empty((100))

In [33]: b[:] = a[:,0]

In [34]: b.strides
Out[34]: (8,)
Sign up to request clarification or add additional context in comments.

1 Comment

As a side note to NPE's answer, in the first case, the numpy.empty((100)) array is discarded, because b no longer points to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.