วิธีเลือกคอลัมน์ตามดัชนีใน pandas dataframe


บ่อยครั้งที่คุณอาจต้องการเลือกคอลัมน์ใน Pandas DataFrame ตามค่าดัชนี

หากคุณต้องการเลือกคอลัมน์ตามการจัดทำดัชนีจำนวนเต็ม คุณสามารถใช้ฟังก์ชัน .iloc ได้

หากคุณต้องการเลือกคอลัมน์ตามการจัดทำดัชนีป้ายกำกับ คุณสามารถใช้ฟังก์ชัน .loc ได้

บทช่วยสอนนี้ให้ตัวอย่างวิธีใช้แต่ละฟังก์ชันเหล่านี้ในทางปฏิบัติ

ตัวอย่างที่ 1: เลือกคอลัมน์ตามการจัดทำดัชนีจำนวนเต็ม

รหัสต่อไปนี้แสดงวิธีสร้าง DataFrame แพนด้าและใช้ .iloc เพื่อเลือกคอลัมน์ที่มีค่าดัชนีจำนวนเต็ม 3 :

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B'],
                   ' points ': [11, 7, 8, 10, 13, 13],
                   ' assists ': [5, 7, 7, 9, 12, 9],
                   ' rebounds ': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

	team points assists rebounds
0 A 11 5 11
1 To 7 7 8
2 to 8 7 10
3 B 10 9 6
4 B 13 12 6
5 B 13 9 5

#select column with index position 3
df. iloc [:, 3]

0 11
1 8
2 10
3 6
4 6
5 5
Name: rebounds, dtype: int64

เราสามารถใช้ไวยากรณ์ที่คล้ายกันเพื่อเลือกหลายคอลัมน์:

 #select columns with index positions 1 and 3
df. iloc [:, [1, 3]]


        rebound points
0 11 11
1 7 8
2 8 10
3 10 6
4 13 6
5 13 5

หรือเราสามารถเลือกคอลัมน์ทั้งหมดในช่วง:

 #select columns with index positions in range 0 through 3
df. iloc [:, 0:3]

        team points assists
0 to 11 5
1 To 7 7
2 to 8 7
3 B 10 9
4 B 13 12
5 B 13 9

ตัวอย่างที่ 2: เลือกคอลัมน์ตามการจัดทำดัชนีป้ายกำกับ

รหัสต่อไปนี้แสดงวิธีสร้าง DataFrame แพนด้าและใช้ .loc เพื่อเลือกคอลัมน์ที่มีป้ายกำกับดัชนีเป็น “bounces” :

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B'],
                   ' points ': [11, 7, 8, 10, 13, 13],
                   ' assists ': [5, 7, 7, 9, 12, 9],
                   ' rebounds ': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

	team points assists rebounds
0 A 11 5 11
1 To 7 7 8
2 to 8 7 10
3 B 10 9 6
4 B 13 12 6
5 B 13 9 5

#select column with index label 'rebounds'
df. loc [:, ' rebounds ']

0 11
1 8
2 10
3 6
4 6
5 5
Name: rebounds, dtype: int64

เราสามารถใช้ไวยากรณ์ที่คล้ายกันเพื่อเลือกหลายคอลัมน์ที่มีป้ายกำกับดัชนีต่างกัน:

 #select the columns with index labels 'points' and 'rebounds'
df. loc [:,[' points ',' rebounds ']]

	rebound points
0 11 11
1 7 8
2 8 10
3 10 6
4 13 6
5 13 5

หรือเราสามารถเลือกคอลัมน์ทั้งหมดในช่วง:

 #select columns with index labels between 'team' and 'assists'
df. loc [:, ' team ':' assists ']

	team points assists
0 to 11 5
1 To 7 7
2 to 8 7
3 B 10 9
4 B 13 12
5 B 13 9

ที่เกี่ยวข้อง: Pandas loc กับ iloc: อะไรคือความแตกต่าง?

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:

วิธีจัดกลุ่มตามดัชนีใน Pandas DataFrame
วิธีเลือกแถวตามดัชนีใน Pandas DataFrame
วิธีรับหมายเลขแถวใน Pandas DataFrame
วิธีลบคอลัมน์ดัชนีใน Pandas DataFrame

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *