NumPy 배열에서 특정 행과 열 선택
나는 내가 여기서 어리석은 일을 잘못하고 있는지 알아 내려고 미쳐 가고 있습니다.
저는 NumPy를 사용하고 있으며, 선택하려는 특정 행 인덱스와 특정 열 인덱스가 있습니다. 내 문제의 요지는 다음과 같습니다.
import numpy as np
a = np.arange(20).reshape((5,4))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19]])
# If I select certain rows, it works
print a[[0, 1, 3], :]
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [12, 13, 14, 15]])
# If I select certain rows and a single column, it works
print a[[0, 1, 3], 2]
# array([ 2, 6, 14])
# But if I select certain rows AND certain columns, it fails
print a[[0,1,3], [0,2]]
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ValueError: shape mismatch: objects cannot be broadcast to a single shape
왜 이런 일이 발생합니까? 확실히 1, 2, 4 번째 행과 1, 3 번째 열을 선택할 수 있어야합니까? 내가 기대하는 결과는 다음과 같습니다.
a[[0,1,3], [0,2]] => [[0, 2],
[4, 6],
[12, 14]]
멋진 인덱싱을 사용하려면 각 차원에 대한 모든 인덱스를 제공해야합니다. 첫 번째 인덱스에는 3 개의 인덱스를 제공하고 두 번째 인덱스에는 2 개만 제공하므로 오류가 발생합니다. 다음과 같이하고 싶습니다.
>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
물론 글을 쓰는 것은 고통스럽기 때문에 방송을 통해 다음과 같은 도움을받을 수 있습니다.
>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
목록이 아닌 배열로 인덱싱하면 훨씬 간단합니다.
>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.
>>> a[[0,1,3], :] # Returns the rows you want
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]] # Selects the columns you want as well
array([[ 0, 2],
[ 4, 6],
[12, 14]])
[Edit] The built-in method: np.ix_
I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:
Using ix_ one can quickly construct index arrays that will index the cross product.
a[np.ix_([1,3],[2,5])]returns the array[[a[1,2] a[1,5]], [a[3,2] a[3,5]]].
So you use it like this:
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:
>>> np.ix_([0,1,3], [0,2])
(array([[0],
[1],
[3]]), array([[0, 2]]))
Also, as MikeC says in a comment, np.ix_ has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:
>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a
array([[-1, 1, -1, 3],
[-1, 5, -1, 7],
[ 8, 9, 10, 11],
[-1, 13, -1, 15],
[16, 17, 18, 19]])
USE:
>>> a[[0,1,3]][:,[0,2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
OR:
>>> a[[0,1,3],::2]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
참고URL : https://stackoverflow.com/questions/22927181/selecting-specific-rows-and-columns-from-numpy-array
'program story' 카테고리의 다른 글
| Bootstrap 3에서 기둥을 쌓을 때 수직 공간 (0) | 2020.11.11 |
|---|---|
| TeamCity에서 배포 한 내 nuget 패키지로 디버그하는 방법은 무엇입니까? (0) | 2020.11.11 |
| PowerShell에서 CMD 명령 실행 (0) | 2020.11.11 |
| 오류 : ggplot2 및 data.table에 대한 패키지 또는 네임 스페이스로드 실패 (0) | 2020.11.11 |
| TensorFlow : InternalError : Blas SGEMM 시작 실패 (0) | 2020.11.11 |