Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
When will a new array be created when I use the slice operator in Numpy?

Today, when I used the slice operator to modify an array, I found that the following operations got different results, although operations seemed to be the same.

import numpy as np
a = np.array([[1,2,3],[0,5,4],[4,5,3],[5,8,7]])
print(a)
a[[0,1],:][0:2,:] = [[11,12,13],[8,9,7]]
print(a)
a[0:2,:][[0,1],:] = [[11,12,13],[8,9,7]]
print(a)

the results are following:

[[1 2 3]
[0 5 4]
[4 5 3]
[5 8 7]]

[[1 2 3]
[0 5 4]
[4 5 3]
[5 8 7]]

[[11 12 13]
[8 9 7]
[4 5 3]
[5 8 7]]

I guess that "a[[0,1],:]" creates a new array, and "a[0:2,:]" doesn't. But why? I am confused. I want to know under what conditions a new array will be created when I use the slice operator.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

a[[0,1],:] with a list is "advanced indexing". It makes a copy. The [0,1] is not a slice.

a[0:2,:] with a slice is "basic indexing". It returns a view.

a[[0,1],:][0:2,:] = ... tries to modify that copy, and doesn't affect a. a[0:2,:][[0,1],:] = ... tries to modify the view, and thus also modifies a.

a[[0,1],:] = ... will successfully modify a.

It's a good idea of avoid the the indexing sequence when setting values. a[...][...] = .... As this example shows, sometimes it works, other times not. If you avoid it entirely you won't have to worry about which works.

Even when fetching values the double indexing is less than ideal. It always works, but can be harder to understand.

a[0:2,:][[0,1],:] = [[11,12,13],[8,9,7]]

is evaluated as

a.__getitem__((slice(0,2), slice(None))).
  __setitem__(([0,1], slice(None)), [[11,12,13],[8,9,7] )

The getitem is performed first, and the setitem is applied to that result. So when chaining indexing it is crucial that you understand what that first indexing does.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda