ในการเติมค่า NaN ในดัชนี (Index) ด้วยค่าที่ระบุ ให้ใช้เมธอด index.fillna() ใน Pandas
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
import numpy as np
2. สร้างดัชนีที่มี NaN
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. เติมค่า NaN ด้วยค่าที่ระบุ
print("\nIndex object after filling NaN value...\n", index.fillna('Amit'))
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
import numpy as np
# สร้างดัชนีที่มี NaN
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# เติม NaN ด้วย 'Amit'
print("\nIndex object after filling NaN value...\n", index.fillna('Amit'))
ผลลัพธ์
Pandas Index... Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64')
Number of elements in the index... 9
The dtype object... float64
Index object after filling NaN value... Index([50.0, 10.0, 70.0, 'Amit', 90.0, 50.0, 'Amit', 'Amit', 30.0], dtype='object')
คำอธิบาย
fillna() สร้างดัชนีใหม่ที่แทนที่ NaN ด้วยค่าที่ระบุ ('Amit') สังเกตว่า dtype เปลี่ยนจาก float64 เป็น object เนื่องจากมีทั้งตัวเลขและสตริง