ส่งคืนดัชนีต่ำสุดในสตริงที่พบซับสตริงย่อยโดยใช้เมธอด numpy.char.index() ใน Python Numpy เมธอดส่งคืนอาร์เรย์เอาต์พุตของ int เพิ่ม ValueError หากไม่พบย่อย พารามิเตอร์แรกคืออาร์เรย์อินพุต พารามิเตอร์ที่สองคือสตริงย่อยที่จะค้นหา
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import numpy as np
สร้างอาร์เรย์หนึ่งมิติของสตริง -
arr = np.array(['KATIE', 'KATE'])
กำลังแสดงอาร์เรย์ของเรา -
print("Array...\n",arr) รับประเภทข้อมูล -
print("\nArray datatype...\n",arr.dtype)
รับขนาดของอาร์เรย์ -
print("\nArray Dimensions...\n",arr.ndim) รับรูปร่างของอาร์เรย์ -
print("\nOur Array Shape...\n",arr.shape)
รับจำนวนขององค์ประกอบของอาร์เรย์ -
print("\nNumber of elements in the Array...\n",arr.size) ส่งคืนดัชนีต่ำสุดในสตริงที่พบสตริงย่อยโดยใช้เมธอด numpy.char.index() -
print("\nResult (index() method)...\n",np.char.index(arr, 'AT'))
ตัวอย่าง
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'KATE'])
# Displaying our array
print("Array...\n",arr)
# Get the datatype
print("\nArray datatype...\n",arr.dtype)
# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)
# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)
# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)
# Return the lowest index in the string where substring sub is found using the numpy.char.index() method in Python Numpy
print("\nResult (index() method)...\n",np.char.index(arr, 'AT')) ผลลัพธ์
Array... ['KATIE' 'KATE'] Array datatype... <U5 Array Dimensions... 1 Our Array Shape... (2,) Number of elements in the Array... 2 Result (index() method)... [1 1]