Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - สร้าง DataFrame จากระดับของ MultiIndex และแทนที่ชื่อระดับ

บทนำ

ใช้ MultiIndex.to_frame() พร้อมพารามิเตอร์ name เพื่อสร้าง DataFrame และตั้งชื่อคอลัมน์ใหม่

ขั้นตอน

1. นำเข้าไลบรารีและสร้าง MultiIndex

import pandas as pd
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
multiIndex = pd.MultiIndex.from_arrays(arrays)

2. สร้าง DataFrame และตั้งชื่อคอลัมน์เป็น 'One', 'Two'

dataFrame = multiIndex.to_frame(name=['One', 'Two'])

ตัวอย่างโค้ดเต็ม

import pandas as pd

arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
multiIndex = pd.MultiIndex.from_arrays(arrays)

print("The Multi-index...\n", multiIndex)
print("\nThe levels in Multi-index...\n", multiIndex.levels)

dataFrame = multiIndex.to_frame(name=['One', 'Two'])
print("\nThe DataFrame...\n", dataFrame)

ผลลัพธ์

The Multi-index...
MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')])

The levels in Multi-index...
[[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]

The DataFrame...
    One     Two
1   John    1    John
2   Tim     2     Tim
3   Jacob   3   Jacob
4   Chris   4   Chris

คำอธิบาย

  • to_frame() แปลง MultiIndex เป็น DataFrame โดยแต่ละระดับกลายเป็นคอลัมน์
  • name=['One', 'Two'] ตั้งชื่อคอลัมน์ใหม่แทนชื่อเดิม (หรือ None ถ้าไม่มีชื่อ)
  • Index ของ DataFrame จะเป็นค่าของระดับแรก (ถ้าไม่ได้ตั้งค่า index=False)