Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Tạo DataFrame với các cấp của MultiIndex dưới dạng cột nhưng tránh đặt chỉ mục của DataFrame trả về

Để tạo DataFrame với các cấp của MultiIndex dưới dạng cột, hãy sử dụng multiIndex.to_frame () . Chỉ mục tham số được đặt Sai để tránh thiết lập chỉ mục của DataFrame trả về

Đầu tiên, hãy nhập các thư viện được yêu cầu -

import pandas as pd

MultiIndex là một đối tượng chỉ mục đa cấp hoặc phân cấp cho các đối tượng gấu trúc. Tạo mảng -

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

Tham số "tên" đặt tên cho mỗi cấp chỉ mục. From_arrays () được sử dụng để tạo MultiIndex -

multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

Tạo DataFrame với các cấp của MultiIndex dưới dạng cột bằng cách sử dụng to_frame (). Sử dụng tham số "chỉ mục" và đặt thành "Sai" để tránh đặt chỉ mục của DataFrame trả về -

dataFrame = multiIndex.to_frame(index=False)

Ví dụ

Sau đây là mã -

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)

# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
# Use the "index" parameter and set it to "False" to avoid setting the index of the returned #DataFrame
dataFrame = multiIndex.to_frame(index=False)

# Return the DataFrame
print("\nThe DataFrame...\n",dataFrame)

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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']]

The DataFrame...
   ranks   student
0      1      John
1      2       Tim
2      3     Jacob
3      4     Chris