การตรวจสอบว่า Index มีเฉพาะข้อมูลตัวเลข
ใช้เมธอด index.is_numeric() ตรวจสอบว่า Index ประกอบด้วยข้อมูลตัวเลขเท่านั้น (รวม int, float, และ NaN)
ขั้นตอน
- นำเข้า pandas และ numpy
- สร้าง Index ที่มี int, float, และ NaN
- แสดง Index
- ใช้
is_numeric()ตรวจสอบ
ตัวอย่างโค้ด
import pandas as pd
import numpy as np
# สร้าง Index มี int, float, NaN
index = pd.Index([5, 10.2, 25, 50, 75.2, 100, np.nan])
# แสดง Index
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบและ dtype
print("\nNumber of elements in the index...\n", index.size)
print("\nThe dtype object...\n", index.dtype)
# ตรวจสอบว่ามีเฉพาะข้อมูลตัวเลข
print("\nIndex values only consists of numeric data?\n", index.is_numeric())
ผลลัพธ์
Pandas Index... Float64Index([5.0, 10.2, 25.0, 50.0, 75.2, 100.0, nan], dtype='float64') Number of elements in the index... 7 The dtype object... float64 Index values only consists of numeric data? True
คำอธิบาย
แม้จะมี np.nan ก็ยังถือเป็นข้อมูลตัวเลข (float) ดังนั้น is_numeric() คืนค่า True