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

Python Pandas: ดูชนิดข้อมูลของคอลัมน์ด้วย info()

บทนำ

เมธอด info() ของ DataFrame แสดงข้อมูลสรุปครบถ้วน: จำนวนแถว, คอลัมน์, ชนิดข้อมูล (dtype), ค่า non-null, และ memory usage เหมาะสำหรับการสำรวจข้อมูลเบื้องต้น (EDA)

ตัวอย่างโค้ด


import pandas as pd

df = pd.DataFrame({
    "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],
    "Roll Number": [5, 10, 3, 8, 2, 9, 6],
    "Score": [85.5, 92.0, 78.5, 88.0, 95.5, 70.0, 82.5],
    "Passed": [True, True, True, True, True, False, True],
    "Enrollment": pd.to_datetime(['2020-01-15', '2020-02-20', '2020-01-10', 
                                   '2020-03-05', '2019-12-01', '2020-01-25', '2020-02-10'])
})

print("DataFrame:")
print(df)

print("\n=== DataFrame.info() ===")
df.info()

print("\n=== DataFrame.dtypes ===")
print(df.dtypes)

print("\n=== DataFrame.memory_usage() ===")
print(df.memory_usage(deep=True))

ผลลัพธ์


DataFrame:
   Student  Roll Number  Score  Passed Enrollment
0     Jack            5   85.5    True 2020-01-15
1    Robin           10   92.0    True 2020-02-20
2      Ted            3   78.5    True 2020-01-10
3     Marc            8   88.0    True 2020-03-05
4  Scarlett            2   95.5    True 2019-12-01
5      Kat            9   70.0   False 2020-01-25
6     John            6   82.5    True 2020-02-10

=== DataFrame.info() ===

RangeIndex: 7 entries, 0 to 6
Data columns (total 5 columns):
 #   Column       Non-Null Count  Dtype
---  ------       --------------  -----
 0   Student      7 non-null      object
 1   Roll Number  7 non-null      int64
 2   Score        7 non-null      float64
 3   Passed       7 non-null      bool
 4   Enrollment   7 non-null      datetime64[ns]
dtypes: bool(1), datetime64[ns](1), float64(1), int64(1), object(1)
memory usage: 488.0+ bytes

=== DataFrame.dtypes ===
Student        object
Roll Number     int64
Score         float64
Passed           bool
Enrollment    datetime64[ns]
dtype: object

=== DataFrame.memory_usage() ===
Index          128
Student        240
Roll Number     56
Score           56
Passed          56
Enrollment      56
dtype: int64

พารามิเตอร์ของ info()

พารามิเตอร์คำอธิบายค่าเริ่มต้น
verboseTrue = แสดงทุกคอลัมน์, False = สรุปเฉพาะ dtype countsTrue
memory_usageTrue/False/'deep' - แสดง memory usageTrue
show_countsTrue/False - แสดง non-null countsTrue
null_countsTrue/False - แสดง null counts แทน non-nullFalse

การเข้าถึง dtype โดยตรง


# Series ของ dtypes
print(df.dtypes)
# Student          object
# Roll Number       int64
# ...

# dtype ของคอลัมน์เดียว
print(df['Score'].dtype)  # float64

# ตรวจสอบ dtype
print(df['Score'].dtype == 'float64')  # True
print(pd.api.types.is_numeric_dtype(df['Score']))  # True

สรุป

df.info() ให้ภาพรวมข้อมูลครบถ้วนในคำสั่งเดียว สำหรับการเขียนโปรแกรม ใช้ df.dtypes (Series) หรือ df['col'].dtype (dtype object) ร่วมกับ pd.api.types.is_*_dtype() สำหรับการตรวจสอบแบบ programmatic