해결 방법: 정수 스칼라 배열만 스칼라 인덱스로 변환할 수 있습니다.
Python을 사용할 때 발생할 수 있는 오류는 다음과 같습니다.
TypeError : only integer scalar arrays can be converted to a scalar index
이 오류는 일반적으로 다음 두 가지 이유 중 하나로 인해 발생합니다.
1. 목록에서 배열 인덱싱을 수행하려고 했습니다.
2. 잘못된 구문을 사용하여 두 행렬을 연결하려고 했습니다.
다음 예에서는 두 시나리오 모두에서 이러한 오류를 방지하는 방법을 보여줍니다.
예 1: 목록에서 배열 인덱싱을 수행하려고 했습니다.
matplotlib에 범례와 레이블이 있는 꺾은선형 차트를 생성하기 위해 다음 코드를 사용한다고 가정해 보겠습니다.
import numpy as np
#create a list of values
data = [3, 5, 5, 7, 8, 10, 12, 14]
#choose 3 random values from list
random_values = np. random . choice (range(len(data)), size= 2 )
#attempt to use indexing to access elements in list
random_vals = data[random_values. astype (int)]
#view results
random_vals
TypeError : only integer scalar arrays can be converted to a scalar index
목록에서 배열 인덱싱을 사용하려고 했기 때문에 오류가 발생했습니다.
이 오류를 방지하려면 먼저 다음과 같이 np.array() 를 사용하여 목록을 NumPy 배열로 변환해야 합니다.
import numpy as np
#create a list of values
data = [3, 5, 5, 7, 8, 10, 12, 14]
#choose 3 random values from list
random_values = np. random . choice (range(len(data)), size= 2 )
#attempt to use indexing to access elements in list
random_vals = np. array (data)[random_values. astype (int)]
#view results
random_vals
array([5, 7])
이번에는 먼저 목록을 NumPy 배열로 변환했기 때문에 오류 없이 목록에서 두 개의 값을 무작위로 선택할 수 있습니다.
예 2: 잘못된 구문을 사용하여 두 행렬을 연결하려고 했습니다.
두 개의 NumPy 행렬을 연결하기 위해 다음 코드를 사용한다고 가정해 보겠습니다.
import numpy as np
#create twoNumPy matrices
mat1 = np. matrix ([[3, 5], [5, 7]])
mat2 = np. matrix ([[2, 4], [1, 8]])
#attempt to concatenate both matrices
n.p. concatenate (mat1, mat2)
TypeError : only integer scalar arrays can be converted to a scalar index
concatenate() 함수에 행렬을 튜플로 제공하지 못했기 때문에 오류가 발생했습니다.
이 오류를 방지하려면 다음과 같이 이중 괄호를 사용하여 concatenate() 함수에 튜플 형식의 행렬을 제공해야 합니다.
import numpy as np
#create twoNumPy matrices
mat1 = np. matrix ([[3, 5], [5, 7]])
mat2 = np. matrix ([[2, 4], [1, 8]])
#attempt to concatenate both matrices
n.p. concatenate ((mat1, mat2))
matrix([[3, 5],
[5, 7],
[2, 4],
[1, 8]])
이번에는 오류 없이 두 행렬을 연결하는 데 성공했습니다.
추가 리소스
다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.
Pandas에서 KeyError를 수정하는 방법
해결 방법: ValueError: float NaN을 int로 변환할 수 없습니다.
해결 방법: ValueError: 피연산자를 모양과 함께 브로드캐스트할 수 없습니다.