วิธีแก้ไข: ไม่ได้กำหนดชื่อข้อผิดพลาด 'np'
หนึ่งในข้อผิดพลาดทั่วไปที่คุณอาจพบเมื่อใช้ Python คือ:
NameError : name 'np' is not defined
ข้อผิดพลาดนี้เกิดขึ้นเมื่อคุณนำเข้าไลบรารีหลาม NumPy แต่ล้มเหลวในการนามแฝงว่าเป็น np เมื่อนำเข้า
ตัวอย่างต่อไปนี้แสดงให้เห็นว่าปัญหานี้เกิดขึ้นได้อย่างไร และวิธีการแก้ไข
ตัวอย่างที่ 1: นำเข้า numpy
สมมติว่าคุณนำเข้าไลบรารี NumPy โดยใช้โค้ดต่อไปนี้:
import numpy
หากคุณพยายามกำหนดอาร์เรย์ของค่าจำนวนมาก คุณจะได้รับข้อผิดพลาดต่อไปนี้:
#define numpy array
x = np. random . normal (loc=0, scale=1, size=20)
#attempt to print values in array
print (x)
Traceback (most recent call last):
----> 1 x = np.random.normal(loc=0, scale=1, size=20)
2 print(s)
NameError : name 'np' is not defined
เพื่อแก้ไขข้อผิดพลาดนี้ คุณต้องระบุนามแฝงของ np เมื่อนำเข้า NumPy:
import numpy as np #define numpy array x = np. random . normal (loc=0, scale=1, size=20) #print values in array print (x) [-0.93937656 -0.49448118 -0.16772964 0.44939978 -0.80577905 0.48042484 0.30175551 -0.15672656 -0.26931062 0.38226115 1.4472055 -0.13668984 -0.74752684 1.6729974 2.25824518 0.77424489 0.67853607 1.46739364 0.14647622 0.87787596]
ตัวอย่างที่ 2: จากการนำเข้าจำนวนมาก *
สมมติว่าคุณนำเข้าฟังก์ชันทั้งหมดจากไลบรารี NumPy โดยใช้โค้ดต่อไปนี้:
from numpy import *
หากคุณพยายามกำหนดอาร์เรย์ของค่าจำนวนมาก คุณจะได้รับข้อผิดพลาดต่อไปนี้:
#define numpy array
x = np. random . normal (loc=0, scale=1, size=20)
#attempt to print values in array
print (x)
Traceback (most recent call last):
----> 1 x = np.random.normal(loc=0, scale=1, size=20)
2 print(s)
NameError : name 'np' is not defined
เพื่อแก้ไขข้อผิดพลาดนี้ คุณต้องระบุนามแฝงของ np เมื่อนำเข้า NumPy:
import numpy as np #define numpy array x = np. random . normal (loc=0, scale=1, size=20) #print values in array print (x) [-0.93937656 -0.49448118 -0.16772964 0.44939978 -0.80577905 0.48042484 0.30175551 -0.15672656 -0.26931062 0.38226115 1.4472055 -0.13668984 -0.74752684 1.6729974 2.25824518 0.77424489 0.67853607 1.46739364 0.14647622 0.87787596]
หรือคุณสามารถเลือกที่จะไม่ใช้ไวยากรณ์ np ได้เลย:
import numpy #define numpy array x = numpy. random . normal (loc=0, scale=1, size=20) #print values in array print (x) [-0.93937656 -0.49448118 -0.16772964 0.44939978 -0.80577905 0.48042484 0.30175551 -0.15672656 -0.26931062 0.38226115 1.4472055 -0.13668984 -0.74752684 1.6729974 2.25824518 0.77424489 0.67853607 1.46739364 0.14647622 0.87787596]
หมายเหตุ: โดยทั่วไปจะใช้ไวยากรณ์ “import numpy as np” เนื่องจากให้วิธีการใช้ฟังก์ชัน NumPy ที่กระชับยิ่งขึ้น แทนที่จะพิมพ์ “numpy” ทุกครั้ง คุณสามารถพิมพ์ “np” ซึ่งจะทำให้อ่านได้เร็วและง่ายกว่า
แหล่งข้อมูลเพิ่มเติม
วิธีแก้ไข: ไม่ได้กำหนด NameError ‘pd’
วิธีแก้ไข: ไม่มีโมดูลชื่อแพนด้า