ในการส่งคืนอาร์เรย์บูลีนที่เป็น True โดยที่องค์ประกอบสตริงในอาร์เรย์เริ่มต้นด้วยคำนำหน้า ให้ใช้เมธอด numpy.char.startswith() ใน Python Numpy เมธอดจะส่งออกอาร์เรย์ของบูล พารามิเตอร์แรกคืออาร์เรย์อินพุต พารามิเตอร์ที่สองคือคำนำหน้า ด้วยพารามิเตอร์เริ่มต้นที่เป็นทางเลือก ให้ทดสอบโดยเริ่มจากตำแหน่งนั้น ด้วยพารามิเตอร์ปลายทางที่ไม่บังคับ ให้หยุดการเปรียบเทียบที่ตำแหน่งนั้น
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import numpy as np
สร้างอาร์เรย์หนึ่งมิติของสตริง -
arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])
กำลังแสดงอาร์เรย์ของเรา -
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) ในการส่งคืนอาร์เรย์บูลีนซึ่งเป็น True โดยที่องค์ประกอบสตริงในอาร์เรย์เริ่มต้นด้วยคำนำหน้า ให้ใช้เมธอด numpy.char.startswith() วิธีการส่งออกอาร์เรย์ของบูล -
print("\nResult (startswith)...\n",np.char.startswith(arr, 'K', start = 0, end = 2)) ตัวอย่าง
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])
# 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)
# To return a boolean array which is True where the string element in array begins with prefix, use the numpy.char.startswith() method in Python Numpy
# The method outputs an array of bools.
print("\nResult (startswith)...\n",np.char.startswith(arr, 'K', start = 0, end = 2)) ผลลัพธ์
Array... ['KATIE' 'JOHN' 'KATE' 'KmY' 'BRAD'] Array datatype... <U5 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result (startswith)... [ True False True True False]