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

Python Pandas - แปลง MultiIndex เป็น Index ของทูเพิลที่มีค่าระดับ

บทนำ

ใช้ MultiIndex.to_flat_index() เพื่อแปลง MultiIndex เป็น Index แบบแบน (flat) ที่แต่ละองค์ประกอบเป็นทูเพิล

ขั้นตอน

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

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

2. แปลงเป็น Flat Index

print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",
      multiIndex.to_flat_index())

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

import pandas as pd

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

print("The Multi-index...\n", multiIndex)
print("\nThe levels in Multi-index...\n", multiIndex.levels)
print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",
      multiIndex.to_flat_index())

ผลลัพธ์

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

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

Converting a MultiIndex to an Index of Tuples containing the level values...
Index([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], dtype='object')

คำอธิบาย

  • to_flat_index() คืนค่า Index ที่แต่ละ element เป็น tuple ของค่าทุกระดับ
  • Index ที่ได้มี dtype='object' และไม่มีชื่อระดับ (names=None)
  • เหมาะสำหรับการ iterate, join, หรือแปลงเป็น list ของ tuples