วิธีแก้ไข: เฉพาะอาร์เรย์สเกลาร์จำนวนเต็มเท่านั้นที่สามารถแปลงเป็นดัชนีสเกลาร์ได้
ข้อผิดพลาดที่คุณอาจพบเมื่อใช้ 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
เราได้รับข้อผิดพลาดเนื่องจากเราพยายามใช้การจัดทำดัชนีอาร์เรย์ในรายการ
เพื่อหลีกเลี่ยงข้อผิดพลาดนี้ อันดับแรกเราต้องแปลงรายการเป็นอาร์เรย์ NumPy โดยใช้ np.array() ดังนี้:
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:
วิธีแก้ไข KeyError ใน Pandas
วิธีแก้ไข: ValueError: ไม่สามารถแปลง float NaN เป็น int
วิธีแก้ไข: ValueError: ตัวถูกดำเนินการไม่สามารถออกอากาศด้วยรูปร่างได้