วิธีแปลง pandas pivottable เป็น dataframe


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

 df = pivot_name. reset_index ()

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

ตัวอย่าง: แปลง PivotTable เป็น DataFrame

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

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   ' position ': ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'],
                   ' points ': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

	team position points
0 A G 11
1 A G 8
2 A F 10
3 A F 6
4 B G 6
5 B G 5
6 B F 9
7 B F 12

เราสามารถใช้โค้ดต่อไปนี้เพื่อสร้างตารางสาระสำคัญที่แสดงคะแนนเฉลี่ยที่ทีมและตำแหน่งทำได้:

 #create pivot table
df_pivot = pd. pivot_table (df, values=' points ', index=' team ', columns=' position ')

#view pivot table
df_pivot

position F G
team		
At 8.0 9.5
B 10.5 5.5

จากนั้นเราสามารถใช้ฟังก์ชัน reset_index() เพื่อแปลงตารางสาระสำคัญนี้เป็น DataFrame ของแพนด้า:

 #convert pivot table to DataFrame
df2 = df_pivot. reset_index ()

#view DataFrame
df2

	team F G
0 to 8.0 9.5
1 B 10.5 5.5

ผลลัพธ์ที่ได้คือ DataFrame แพนด้าที่มีสองแถวและสามคอลัมน์

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

 #convert pivot table to DataFrame
df2. columns = [' team ', ' Forward_Pts ', ' Guard_Pts ']

#view updated DataFrame
df2

        team Forward_Pts Guard_Pts
0 to 8.0 9.5
1 B 10.5 5.5

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

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

Pandas: วิธีปรับรูปร่าง DataFrame จากยาวไปเป็นกว้าง
Pandas: วิธีปรับรูปร่าง DataFrame จากกว้างไปเป็นยาว
นุ่น: วิธีจัดกลุ่มและรวมเป็นหลายคอลัมน์

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

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