วิธีเพิ่มแถวในเมทริกซ์ใน numpy (พร้อมตัวอย่าง)
คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อเพิ่มแถวให้กับเมทริกซ์ใน NumPy:
#add new_row to current_matrix current_matrix = np. vstack ([current_matrix, new_row])
คุณยังสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อเพิ่มเฉพาะแถวลงในเมทริกซ์ที่ตรงตามเงื่อนไขบางประการได้:
#only add rows where first element is less than 10 current_matrix = np. vstack ((current_matrix, new_rows[new_rows[:,0] < 10 ]))
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่างที่ 1: เพิ่มแถวให้กับเมทริกซ์ใน NumPy
รหัสต่อไปนี้แสดงวิธีเพิ่มแถวใหม่ให้กับเมทริกซ์ใน NumPy:
import numpy as np
#define matrix
current_matrix = np. array ([[1,2,3], [4, 5, 6], [7, 8, 9]])
#define row to add
new_row = np. array ([10, 11, 12])
#add new row to matrix
current_matrix = np. vstack ([current_matrix, new_row])
#view updated matrix
current_matrix
array([[ 1, 2, 3],
[4,5,6],
[7, 8, 9],
[10, 11, 12]])
โปรดทราบว่าแถวสุดท้ายถูกเพิ่มลงในเมทริกซ์สำเร็จแล้ว
ตัวอย่างที่ 2: เพิ่มแถวลงในเมทริกซ์ตามเงื่อนไข
รหัสต่อไปนี้แสดงวิธีการเพิ่มแถวใหม่หลายแถวให้กับเมทริกซ์ที่มีอยู่ตามเงื่อนไขเฉพาะ:
import numpy as np
#define matrix
current_matrix = np. array ([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
#define potential new rows to add
new_rows = np. array ([[6, 8, 10], [8, 10, 12], [10, 12, 14]])
#only add rows where first element in row is less than 10
current_matrix = np. vstack ((current_matrix, new_rows[new_rows[:,0] < 10 ]))
#view updated matrix
current_matrix
array([[ 1, 2, 3],
[4,5,6],
[7, 8, 9],
[6, 8, 10],
[8, 10, 12]])
เพิ่มเฉพาะแถวที่มีองค์ประกอบแรกน้อยกว่า 10 เท่านั้น
หมายเหตุ : คุณสามารถดูเอกสารออนไลน์ฉบับเต็มสำหรับฟังก์ชัน vstack() ได้ที่นี่
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ใน NumPy:
วิธีค้นหาดัชนีค่าในอาร์เรย์ NumPy
วิธีเพิ่มอาร์เรย์ Numpy ให้กับ Pandas DataFrame
วิธีแปลงอาร์เรย์ NumPy เป็น Pandas DataFrame