Pandas: วิธีตั้งค่าคอลัมน์เป็นดัชนี
คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อตั้งค่าคอลัมน์ใน DataFrame แพนด้าเป็นดัชนี:
#set one column as index df. set_index (' col1 ') #set multiple columns as multi index df. set_index ([' col1 ',' col2 '])
ตัวอย่างต่อไปนี้แสดงวิธีการใช้ไวยากรณ์นี้ในทางปฏิบัติกับ DataFrame ต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [5, 7, 7, 9, 12, 9], ' assists ': [11, 8, 10, 6, 6, 5], ' team ': ['A', 'B', 'C', 'D', 'E', 'F'], ' conference ': [1, 2, 3, 4, 5, 6]}) #view DataFrame df points assists team conference 0 5 11 A 1 1 7 8 B 2 2 7 10 C 3 3 9 6 D 4 4 12 6 E 5 5 9 5 F 6
ตัวอย่างที่ 1: ตั้งค่าคอลัมน์เป็นดัชนี
รหัสต่อไปนี้แสดงวิธีการตั้งค่าคอลัมน์ของ Pandas DataFrame เป็นดัชนี:
df. set_index (' team ') conference attendance points team A 5 11 1 B 7 8 2 C 7 10 3 D 9 6 4 E 12 6 5 F 9 5 6
ตัวอย่างที่ 2: ตั้งค่าหลายคอลัมน์เป็นดัชนี
รหัสต่อไปนี้แสดงวิธีกำหนดหลายคอลัมน์ของ pandas DataFrame ให้เป็นหลายดัชนี: :
df. set_index ([' team ',' conference '])
assist points
team conference
A 1 5 11
B 2 7 8
C 3 7 10
D 4 9 6
E 5 12 6
F 6 9 5
แหล่งข้อมูลเพิ่มเติม
วิธีเปลี่ยนชื่อดัชนีใน Pandas DataFrame
วิธีลบแถวตามดัชนีใน Pandas
วิธีลบคอลัมน์ตามดัชนีใน Pandas