Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - แปลง Array สตริงเป็น Array Float ด้วย NumPy

สตริงใน Python ล้อมรอบด้วยเครื่องหมายคำพูดเดี่ยวหรือคู่ การแปลงอาร์เรย์สตริงเป็นอาร์เรย์ตัวเลขจำเป็นสำหรับการคำนวณเชิงตัวเลข

ตัวอย่างโค้ด

1. ใช้ astype() (แนะนำ - เรียบง่ายที่สุด)


import numpy as np

ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
print("initial array:", ini_array)

# แปลงเป็น float
res = ini_array.astype(np.float64)
print("final array:", res)

2. ใช้ np.fromstring()


import numpy as np

ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
print("initial array:", ini_array)

# รวมเป็นสตริงเดียวแล้ว parse
ini_string = ', '.join(ini_array)
res = np.fromstring(ini_string, dtype=np.float64, sep=', ')
print("final array:", res)

3. ใช้ np.asarray()


import numpy as np

ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
print("initial array:", ini_array)

final_array = np.asarray(ini_array, dtype=np.float64, order='C')
print("final array:", final_array)

ผลลัพธ์


[1.1 1.5 2.7 8.9]

สรุปและแนะนำ

วิธีข้อดีข้อควรระวัง
astype()ตรงไปตรงมา เร็ว อ่านง่าย รองรับหลาย dtype-
asarray()ไม่ copy ถ้าเป็น array อยู่แล้ว รองรับ orderพฤติกรรมซับซ้อนกว่า
fromstring()parse สตริงโดยตรง ไม่ต้องสร้าง list ก่อนต้อง join ก่อน สำหรับ 1D เท่านั้น

แปลง Python List ธรรมดา (ไม่ใช่ NumPy)


# ใช้ list comprehension (ไม่ต้อง numpy)
str_list = ["1.1", "1.5", "2.7", "8.9"]
float_list = [float(x) for x in str_list]
print(float_list)  # [1.1, 1.5, 2.7, 8.9]

# ใช้ map
float_list = list(map(float, str_list))

จัดการค่าที่แปลงไม่ได้


import numpy as np

def safe_convert(arr):
    """แปลงอย่างปลอดภัย ค่าที่แปลงไม่ได้จะกลายเป็น NaN"""
    result = []
    for x in arr:
        try:
            result.append(float(x))
        except ValueError:
            result.append(np.nan)
    return np.array(result)

# หรือใช้ pandas (ทรงพลังกว่า)
import pandas as pd
pd.to_numeric(["1.1", "abc", "2.5"], errors='coerce')