วิธีการแปลงดัชนีเป็นคอลัมน์ใน pandas (พร้อมตัวอย่าง)


คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อแปลงดัชนีของ DataFrame แพนด้าเป็นคอลัมน์:

 #convert index to column
df. reset_index (inplace= True )

หากคุณมี Pandas MultiIndex DataFrame คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อแปลงระดับดัชนีเฉพาะเป็นคอลัมน์:

 #convert specific level of MultiIndex to column
df. reset_index (inplace= True ,level=[' Level1 '])

ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ

ตัวอย่างที่ 1: แปลงดัชนีเป็นคอลัมน์

รหัสต่อไปนี้แสดงวิธีการแปลงดัชนีของ DataFrame แพนด้าเป็นคอลัมน์:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19],
                   ' assists ': [5, 7, 7, 9, 12],
                   ' rebounds ': [11, 8, 10, 6, 6]})

#view DataFrame
df

points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6

#convert index to column
df. reset_index (inplace= True )

#view updated DataFrame
df

	index points assists rebounds
0 0 25 5 11
1 1 12 7 8
2 2 15 7 10
3 3 14 9 6
4 4 19 12 6

ตัวอย่างที่ 2: แปลง MultiIndex เป็นคอลัมน์

สมมติว่าเรามีแพนด้า MultiIndex DataFrame ดังต่อไปนี้:

 import pandas as pd

#createDataFrame
index_names = pd. MultiIndex . from_tuples ([('Level1','Lev1', 'L1'),
                                       ('Level2','Lev2', 'L2'),
                                       ('Level3','Lev3', 'L3'),
                                       ('Level4','Lev4', 'L4')],
                                       names=['Full','Partial', 'ID'])

data = {' Store ': ['A','B','C','D'],
        ' Sales ': [17, 22, 29, 35]}

df = pd. DataFrame (data, columns = [' Store ',' Sales '], index=index_names)

#view DataFrame
df

                    Store Sales
Full Partial ID		
Level1 Lev1 L1 A 17
Level2 Lev2 L2 B 22
Level3 Lev3 L3 C 29
Level4 Lev4 L4 D 35

รหัสต่อไปนี้แสดงวิธีการแปลง MultiIndex แต่ละระดับเป็นคอลัมน์ใน Pandas DataFrame:

 #convert all levels of index to columns
df. reset_index (inplace= True )

#view updated DataFrame
df

        Full Partial ID Store Sales
0 Level1 Lev1 L1 A 17
1 Level2 Lev2 L2 B 22
2 Level3 Lev3 L3 C 29
3 Level4 Lev4 L4 D 35

นอกจากนี้เรายังสามารถใช้โค้ดต่อไปนี้เพื่อแปลงเฉพาะระดับ MultiIndex ที่ระบุเป็นคอลัมน์ได้:

 #convert just 'ID' index to column in DataFrame
df. reset_index (inplace= True ,level=[' ID '])

#view updated DataFrame
df

		ID Store Sales
Full Partial			
Level1 Lev1 L1 A 17
Level2 Lev2 L2 B 22
Level3 Lev3 L3 C 29
Level4 Lev4 L4 D 35

โปรดทราบว่าเฉพาะระดับ “ID” เท่านั้นที่ถูกแปลงเป็นคอลัมน์ใน DataFrame

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

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

วิธีการตั้งค่าคอลัมน์เป็นดัชนีใน Pandas
วิธีลบคอลัมน์ตามดัชนีใน Pandas
วิธีจัดเรียง DataFrame ตามดัชนีและคอลัมน์ใน Pandas

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

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