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

Python Pandas: เลือกคอลัมน์ตามชนิดข้อมูลด้วย select_dtypes()

บทนำ

เมธอด select_dtypes() ช่วยกรองคอลัมน์ใน DataFrame ตามชนิดข้อมูล (dtype) ได้อย่างสะดวก ใช้พารามิเตอร์ include หรือ exclude

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


import pandas as pd

# สร้าง DataFrame หลายชนิดข้อมูล
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]
})

print("DataFrame:")
print(df)
print("\nInfo:")
print(df.info())

# เลือกคอลัมน์ชนิด object (string)
obj_cols = df.select_dtypes(include=['object']).columns
print(f"\nคอลัมน์ object: {obj_cols.tolist()}")

# เลือกคอลัมน์ชนิด int64
int_cols = df.select_dtypes(include=['int64']).columns
print(f"คอลัมน์ int64: {int_cols.tolist()}")

# เลือกคอลัมน์ตัวเลขทั้งหมด (int + float)
num_cols = df.select_dtypes(include=['number']).columns
print(f"คอลัมน์ตัวเลข (number): {num_cols.tolist()}")

# เลือกคอลัมน์ boolean
bool_cols = df.select_dtypes(include=['bool']).columns
print(f"คอลัมน์ boolean: {bool_cols.tolist()}")

# Exclude: เลือกทุกอย่างยกเว้น object
non_obj = df.select_dtypes(exclude=['object']).columns
print(f"ไม่ใช่ object: {non_obj.tolist()}")

ผลลัพธ์


DataFrame:
   Student  Roll Number  Score  Passed
0     Jack            5   85.5    True
1    Robin           10   92.0    True
2      Ted            3   78.5    True
3     Marc            8   88.0    True
4  Scarlett            2   95.5    True
5      Kat            9   70.0   False
6     John            6   82.5    True

Info:

RangeIndex: 7 entries, 0 to 6
Data columns (total 4 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
dtypes: bool(1), float64(1), int64(1), object(1)
memory usage: 320.0+ bytes

คอลัมน์ object: ['Student']
คอลัมน์ int64: ['Roll Number']
คอลัมน์ตัวเลข (number): ['Roll Number', 'Score']
คอลัมน์ boolean: ['Passed']
ไม่ใช่ object: ['Roll Number', 'Score', 'Passed']

Dtype Strings ที่ใช้บ่อย

Dtype Stringความหมายตัวอย่าง
'object'String / mixed'text', mixed types
'int64', 'int32', 'int'จำนวนเต็ม1, 2, 3
'float64', 'float32', 'float'ทศนิยม1.5, 3.14
'number'ตัวเลขทุกชนิด (int + float)-
'bool'BooleanTrue, False
'datetime64', 'datetimetz'DatetimeTimestamp
'timedelta64'Time differenceTimedelta
'category'Categoricalpd.Categorical

การใช้งานกับ NumPy dtype objects


import numpy as np

# ใช้ numpy dtype โดยตรงได้
int_cols = df.select_dtypes(include=[np.int64, np.int32]).columns
float_cols = df.select_dtypes(include=[np.floating]).columns

สรุป

select_dtypes(include=[...]) และ select_dtypes(exclude=[...]) เป็นวิธีมาตรฐานในการเลือกคอลัมน์ตาม dtype รองรับทั้ง string names และ numpy dtype objects เหมาะสำหรับ preprocessing pipeline