Skip to content
Search

NumPy:Indexing

lastmod 2025-02-18created 2025-02-184 edits

How to index NumPy arrays. The community seems to call it Fancy indexing.

  • slice object (:)
  • Ellipsis (...)
  • np.newaxis

Basic indexing

  • Single element indexing
  • Slicing and striding
  • Dimensional indexing tools

Advanced indexing

  • Integer array indexing
  • Boolean array indexing
  • Combining advanced and basic indexing

Caveats when combining indexing methods

  • See ddrm#Calculate the head camber for details.

WARNING

In my personal opinion, to state the conclusion up front: it seems better to reduce complexity by using only the Basic Indexing method with Boolean, or only the Integer Array Indexing method that points to exact positions.

import numpy as np

# 예시 데이터
thresh = np.zeros((10, 10))  # 10x10 크기의 배열로 예시
plate_head_5m, plate_head_2m = 2, 8  # 인덱스 범위 예시
head = thresh[plate_head_5m:plate_head_2m]
head_min = head.argmax(axis=1)

# head_min 위치에 127을 할당
for i, min_idx in enumerate(head_min):
    thresh[plate_head_5m + i, min_idx] = 127

# 결과 출력
print(thresh)

Using a for loop didn't look graceful, so I looked for another way...

thresh[plate_head_5m:plate_head_2m, head_min] = 127

I thought this would work and applied it, but it didn't.

This is because of NumPy's indexing rules. To explain the key difference:

In the case of thresh[plate_head_5m:plate_head_2m, head_min]:

  • The first index plate_head_5m:plate_head_2m specifies the range of rows
  • The second index head_min is a single array
  • NumPy tries to "apply all positions of head_min together to every selected row."

This seems to happen because of the broadcasting rules.

plate_head_5m:plate_head_2m is represented as a slice object. It must be converted to an Integer Array (row_indices) so that it matches the head_min Array values 1:1 to be processed correctly. Use np.arange as below:

import numpy as np

# 예시로 확인해보기
thresh = np.zeros((10, 10))
plate_head_5m, plate_head_2m = 2, 8
head = thresh[plate_head_5m:plate_head_2m]
head_min = np.array([1, 3, 2, 5, 4, 7])  # 예시 head_min 값

# 올바른 벡터화 방식
row_indices = np.arange(plate_head_5m, plate_head_2m)
thresh[row_indices, head_min] = 127

See also

Favorite site

author Zer0 sitemap