Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - ตรวจสอบว่าดัชนีมี NaN หรือไม่ (index.hasnans)

ในการตรวจสอบว่าดัชนี (Index) มีค่า NaN หรือไม่ ให้ใช้คุณสมบัติ index.hasnans ใน Pandas

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd
import numpy as np

2. สร้างดัชนีที่มี NaN

index = pd.Index(['Car', 'Bike', np.nan, 'Car', np.nan, 'Ship'])

3. แสดงดัชนี

print("Pandas Index...\n", index)

4. ตรวจสอบว่ามี NaN หรือไม่

print("\nIs the Pandas index having NaNs?\n", index.hasnans)

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd
import numpy as np

# สร้างดัชนี (มี NaN ใช้ numpy)
index = pd.Index(['Car', 'Bike', np.nan, 'Car', np.nan, 'Ship'])

# แสดงดัชนี
print("Pandas Index...\n", index)

# แสดงอาร์เรย์ของข้อมูล
print("\nArray...\n", index.values)

# ตรวจสอบว่ามี NaN หรือไม่
print("\nIs the Pandas index having NaNs?\n", index.hasnans)

# แสดงรูปร่างของข้อมูล
print("\nA tuple of the shape of underlying data...\n", index.shape)

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', nan, 'Car', nan, 'Ship'], dtype='object')
Array... ['Car' 'Bike' nan 'Car' nan 'Ship']
Is the Pandas index having NaNs? True
A tuple of the shape of underlying data... (6,)

คำอธิบาย

index.hasnans คืนค่า True หากดัชนีมีค่า NaN อย่างน้อยหนึ่งค่า มิฉะนั้นคืนค่า False ทำงานได้กับ NaN จาก numpy และ None