ในการตั้งค่าระดับใน MultiIndex ให้ใช้ MultiIndex.set_levels() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
MultiIndex เป็นวัตถุดัชนีหลายระดับหรือแบบลำดับชั้นสำหรับวัตถุแพนด้า สร้างอาร์เรย์:
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
พารามิเตอร์ "names" จะตั้งชื่อสำหรับแต่ละระดับดัชนี from_arrays() ใช้เพื่อสร้าง MultiIndex -
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) ตั้งค่าระดับใน MultiIndex -
print("\nSet new levels in Multi-index...\n",multiIndex.set_levels([['p', 'q', 'r', 's'], [10, 20, 30, 40]])) ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# display the MultiIndex
print("The Multi-index...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# set the levels in MultiIndex
print("\nSet new levels in Multi-index...\n",multiIndex.set_levels([['p', 'q', 'r', 's'], [10, 20, 30, 40]])) ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
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']]
Set new levels in Multi-index...
MultiIndex([('p', 30),
('q', 40),
('r', 20),
('s', 10)],
names=['ranks', 'student'])