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

เลือกคอลัมน์ DataFrame หลายคอลัมน์ด้วย Regex และ Data Type ใน Pandas

DataFrame คือตาราง 2 มิติ (แถวและคอลัมน์) ต่างจาก Series ที่เป็น 1 มิติ

เลือกคอลัมน์พื้นฐาน

  • df["col"] → Series
  • df[["col"]] → DataFrame
  • df[["col1", "col2"]] → หลายคอลัมน์

ใช้ .filter() เลือกตามชื่อคอลัมน์

  • like: หาชื่อคอลัมน์ที่มี substring นี้
  • regex: ใช้ Regular Expression
  • items: รายการชื่อคอลัมน์ที่แน่นอน
# like
df.filter(like="title")

# regex (คอลัมน์ลงท้ายด้วย t)
df.filter(regex="t$")

# items
df.filter(items=["title", "runtime"])

ใช้ .select_dtypes() เลือกตาม Data Type

  • include: รวมเฉพาะ type ที่ระบุ
  • exclude: ตัด type ที่ระบุออก
# เฉพาะ int
df.select_dtypes(include="int")

# int และ float
df.select_dtypes(include=["int64", "float"])

# ทุก numeric
df.select_dtypes(include="number")

# ตัด object ออก
df.select_dtypes(exclude="object")

สรุป

.filter() สำหรับชื่อคอลัมน์ .select_dtypes() สำหรับชนิดข้อมูล ทั้งคู่คืน DataFrame ใหม่