วิธีค้นหาดัชนีค่าในอาร์เรย์ numpy (พร้อมตัวอย่าง)
คุณสามารถใช้วิธีการต่อไปนี้เพื่อค้นหาตำแหน่งดัชนีของค่าเฉพาะในอาร์เรย์ NumPy:
วิธีที่ 1: ค้นหาตำแหน่งดัชนีค่าทั้งหมด
n.p. where (x== value )
วิธีที่ 2: ค้นหาตำแหน่งดัชนีค่าแรก
n.p. where (x== value )[0][0]
วิธีที่ 3: ค้นหาตำแหน่งดัชนีแรกของหลายค่า
#define values of interest vals = np. array ([ value1 , value2 , value3 ]) #find index location of first occurrence of each value of interest exit = np. argsort (x) go out[np. searchsorted (x, vals, sorter=sorter)]
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติ
วิธีที่ 1: ค้นหาตำแหน่งดัชนีค่าทั้งหมด
รหัสต่อไปนี้แสดงวิธีการค้นหาแต่ละตำแหน่งดัชนีเท่ากับค่าที่กำหนดในอาร์เรย์ NumPy:
import numpy as np #define array of values x = np. array ([4, 7, 7, 7, 8, 8, 8]) #find all index positions where x is equal to 8 n.p. where (x== 8 ) (array([4, 5, 6]),)
จากผลลัพธ์เราจะเห็นว่าตำแหน่งดัชนี 4, 5 และ 6 มีค่าเท่ากับ 8 ทั้งหมด
วิธีที่ 2: ค้นหาตำแหน่งดัชนีค่าแรก
รหัสต่อไปนี้แสดงวิธีการค้นหาตำแหน่งดัชนีแรกเท่ากับค่าที่กำหนดในอาร์เรย์ NumPy:
import numpy as np #define array of values x = np. array ([4, 7, 7, 7, 8, 8, 8]) #find first index position where x is equal to 8 n.p. where (x== 8 )[0][0] 4
จากผลลัพธ์เราจะเห็นว่าค่า 8 ปรากฏครั้งแรกที่ตำแหน่งดัชนี 4
วิธีที่ 3: ค้นหาตำแหน่งดัชนีแรกของหลายค่า
รหัสต่อไปนี้แสดงวิธีค้นหาตำแหน่งดัชนีแรกของหลายค่าในอาร์เรย์ NumPy:
import numpy as np #define array of values x = np. array ([4, 7, 7, 7, 8, 8, 8]) #define values of interest vals = np. array ([4, 7, 8]) #find index location of first occurrence of each value of interest exit = np. argsort (x) go out[np. searchsorted (x, vals, sorter=sorter)] array([0, 1, 4])
จากผลลัพธ์เราจะเห็นได้ว่า:
- ค่า 4 ปรากฏครั้งแรกที่ตำแหน่งดัชนี 0
- ค่า 7 ปรากฏครั้งแรกที่ตำแหน่งดัชนี 1
- ค่า 8 ปรากฏครั้งแรกที่ตำแหน่งดัชนี 4
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ใน NumPy:
วิธีแมปฟังก์ชันกับอาร์เรย์ NumPy
วิธีแปลงอาร์เรย์ NumPy เป็นรายการใน Python
วิธีการคำนวณขนาดของเวกเตอร์โดยใช้ NumPy