Pandas: วิธีเลือกคอลัมน์ตามประเภทข้อมูล
คุณสามารถใช้วิธีการต่อไปนี้เพื่อเลือกคอลัมน์ใน Pandas DataFrame ที่เท่ากับประเภทข้อมูลเฉพาะ:
วิธีที่ 1: เลือกคอลัมน์ที่เท่ากับประเภทข้อมูลเฉพาะ
#select all columns that have an int or float data type
df. select_dtypes (include=[' int ', ' float '])
วิธีที่ 2: เลือกคอลัมน์ที่แตกต่างกันของชนิดข้อมูลเฉพาะ
#select all columns that don't have a bool or object data type
df. select_dtypes (exclude=[' bool ', ' object '])
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีกับ DataFrame แพนด้าต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F'], ' points ': [18, 22, 19, 14, 14, 11], ' assists ': [5, 7, 7, 9, 12, 9], ' minutes ': [10.1, 12.0, 9.0, 8.0, 8.4, 7.5], ' all_star ': [True, False, False, True, True, True]}) #view DataFrame print (df) team points assists minutes all_star 0 A 18 5 10.1 True 1 B 22 7 12.0 False 2 C 19 7 9.0 False 3 D 14 9 8.0 True 4 E 14 12 8.4 True 5 F 11 9 7.5 True
ตัวอย่างที่ 1: เลือกคอลัมน์ที่เท่ากับประเภทข้อมูลเฉพาะ
เราสามารถใช้รหัสต่อไปนี้เพื่อเลือกคอลัมน์ทั้งหมดใน DataFrame ที่มีประเภทข้อมูลเท่ากับ int หรือ float :
#select all columns that have an int or float data type
df. select_dtypes (include=[' int ', ' float '])
minute assist points
0 18 5 10.1
1 22 7 12.0
2 19 7 9.0
3 14 9 8.0
4 14 12 8.4
5 11 9 7.5
โปรดทราบว่าจะเลือกเฉพาะคอลัมน์ที่มีประเภทข้อมูลเท่ากับ int หรือ float เท่านั้น
ตัวอย่างที่ 2: เลือกคอลัมน์ที่แตกต่างกันของประเภทข้อมูลเฉพาะ
เราสามารถใช้รหัสต่อไปนี้เพื่อเลือกคอลัมน์ทั้งหมดใน DataFrame ที่ไม่มีประเภทข้อมูลเท่ากับ bool หรือ object :
#select all columns that don't have a bool or object data type
df. select_dtypes (exclude=[' bool ', ' object '])
minute assist points
0 18 5 10.1
1 22 7 12.0
2 19 7 9.0
3 14 9 8.0
4 14 12 8.4
5 11 9 7.5
โปรดทราบว่าจะเลือกเฉพาะคอลัมน์ที่ไม่มีประเภทข้อมูลเท่ากับ บูล หรือ อ็อบเจ็กต์ เท่านั้น
โปรดทราบว่าคุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อแสดงชนิดข้อมูลของแต่ละคอลัมน์ใน DataFrame:
#display data type of all columns
df. dtypes
team object
int64 dots
assists int64
minutes float64
all_star bool
dtype:object
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
Pandas: วิธีตรวจสอบประเภทของคอลัมน์ทั้งหมดใน DataFrame
Pandas: รับดัชนีของแถวที่มีคอลัมน์ตรงกับค่า
Pandas: วิธีตั้งค่าคอลัมน์เป็นดัชนี