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

Python Pandas - สร้าง DataFrame ด้วยระดับของ MultiIndex เป็นคอลัมน์และแทนที่ชื่อระดับดัชนี


ในการสร้าง DataFrame ที่มีระดับ MultiIndex เป็นคอลัมน์ ให้ใช้ MultiIndex.to_frame() กระบวนการ. แทนที่ชื่อระดับดัชนีโดยใช้ ชื่อ พารามิเตอร์

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import pandas as pd

MultiIndex เป็นวัตถุดัชนีหลายระดับหรือแบบลำดับชั้นสำหรับวัตถุแพนด้า สร้างอาร์เรย์ -

arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

พารามิเตอร์ "names" จะตั้งชื่อสำหรับแต่ละระดับดัชนี from_arrays() ใช้เพื่อสร้าง MultiIndex -

multiIndex = pd.MultiIndex.from_arrays(arrays)

สร้าง DataFrame ที่มีระดับของ MultiIndex เป็นคอลัมน์โดยใช้ to_frame() ใช้พารามิเตอร์ "name" และส่งชื่อเพื่อแทนที่ชื่อระดับดัชนี -

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

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

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)

# display the MultiIndex
print("The Multi-index...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)

# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
# Use the "name" parameter and pass the names to substitute index level names
dataFrame = multiIndex.to_frame(name=['One', 'Two'])

# Display the DataFrame
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