วิธีแปลง pandas series เป็น numpy array (พร้อมตัวอย่าง)
คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อแปลงชุดหมีแพนด้าเป็นอาร์เรย์ NumPy:
seriesName. to_numpy ()
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่างที่ 1: แปลงซีรี่ส์เป็นอาร์เรย์ NumPy
รหัสต่อไปนี้แสดงวิธีการแปลงชุดหมีแพนด้าเป็นอาร์เรย์ NumPy:
import pandas as pd import numpy as np #define series x = pd. Series ([1, 2, 5, 6, 9, 12, 15]) #convert series to NumPy array new_array = x. to_numpy () #view NumPy array new_array array([ 1, 2, 5, 6, 9, 12, 15]) #confirm data type type(new_array) numpy.ndarray
การใช้ฟังก์ชัน type() เรายืนยันว่าชุด pandas ได้ถูกแปลงเป็นอาร์เรย์ NumPy แล้ว
ตัวอย่างที่ 2: แปลงคอลัมน์ DataFrame เป็นอาร์เรย์ NumPy
รหัสต่อไปนี้แสดงวิธีการแปลงคอลัมน์จาก Pandas DataFrame เป็นอาร์เรย์ NumPy:
import pandas as pd import numpy as np #define DataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #convert 'points' column to NumPy array new_array = df[' points ']. to_numpy () #view NumPy array new_array array([25, 12, 15, 14, 19, 23, 25, 29]) #confirm data type type(new_array) numpy.ndarray
เรายังสามารถใช้ dtype() เพื่อตรวจสอบประเภทข้อมูลของอาร์เรย์ NumPy ใหม่ได้:
#check datatype new_array. dtype dtype('int64')
เราจะเห็นว่าอาร์เรย์ NumPy ใหม่เป็นจำนวนเต็ม
แหล่งข้อมูลเพิ่มเติม
วิธีแปลง Pandas DataFrame เป็นอาร์เรย์ NumPy
วิธีแปลง Pandas DataFrame เป็น List
วิธีแปลงพจนานุกรมเป็น Pandas DataFrame