ในการเติมค่า NaN ด้วยค่าที่ระบุในวัตถุดัชนี ให้ใช้ index.fillna() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd import numpy as np
การสร้างดัชนี Pandas ด้วยค่า NaN บางส่วนเช่นกัน -
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
แสดงดัชนีหมีแพนด้า −
print("Pandas Index...\n",index) เติม NaN ด้วยค่าเฉพาะ -
print("\nIndex object after filling NaN value...\n",index.fillna('Amit'))
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd
import numpy as np
# Creating Pandas index with some NaN values as well
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)
# Fill the NaN with some specific value
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')