ในการแสดงว่าองค์ประกอบไหนในดัชนี (Index) เป็น NA (Missing) ให้ใช้เมธอด index.isna() ใน Pandas
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
import numpy as np
2. สร้างดัชนีที่มี NaN
index = pd.Index([5, 65, np.nan, 17, 75, np.nan])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. ตรวจสอบค่าที่เป็น NA
print("\nCheck which entries are NA...\n", index.isna())
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
import numpy as np
# สร้างดัชนีที่มี NaN
index = pd.Index([5, 65, np.nan, 17, 75, np.nan])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# ตรวจสอบค่าที่เป็น NA
print("\nCheck which entries are NA...\n", index.isna())
ผลลัพธ์
Pandas Index... Float64Index([5.0, 65.0, nan, 17.0, 75.0, nan], dtype='float64')
Number of elements in the index... 6
The dtype object... float64
Check which entries are NA... [False False True False False True]
คำอธิบาย
isna() คืนค่าอาร์เรย์ Boolean: True สำหรับค่าที่เป็น NA (NaN/None) False สำหรับค่าที่ไม่ใช่ NA ตำแหน่งที่ 2 และ 5 เป็น NaN จึงเป็น True (ตรงข้ามกับ notna())