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

Python Pandas - ดูชนิดข้อมูลที่อนุมานจากค่า (index.inferred_type)

ในการดูสตริงที่บ่งชี้ชนิดข้อมูลที่อนุมานจากค่าในดัชนี (Index) ให้ใช้คุณสมบัติ index.inferred_type ใน Pandas

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

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

import pandas as pd
import numpy as np

2. สร้างดัชนี (มี NaN)

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

3. แสดงดัชนี

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

4. ดูชนิดข้อมูลที่อนุมาน

print("\nThe inferred type...\n", index.inferred_type)

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

import pandas as pd
import numpy as np

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

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

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

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

# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)

# ดูชนิดข้อมูลที่อนุมาน
print("\nThe inferred type...\n", index.inferred_type)

ผลลัพธ์

Pandas Index... Index(['Car', 'Bike', nan, 'Car', nan, 'Ship', None, None], dtype='object')
Array... ['Car' 'Bike' nan 'Car' nan 'Ship' None None]
Is the Pandas index having NaNs? True
The dtype object... object
The inferred type... Mixed

คำอธิบาย

inferred_type คืนค่าชนิดข้อมูลที่ Pandas อนุมานจากค่าที่มีอยู่ ค่าที่เป็นไปได้ ได้แก่: 'integer', 'floating', 'string', 'boolean', 'datetime', 'timedelta', 'mixed', 'empty' เป็นต้น ในที่นี้คือ 'Mixed' เนื่องจากมีทั้งสตริงและ NaN/None