Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Xếp chồng cột đa cấp trong DataFrame Pandas

Để xếp chồng cột đa cấp, sử dụng phương thức stack(). Trước tiên, nhập thư viện cần thiết:

import pandas as pd

Tạo cột đa cấp:

items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),('Maths', 'Applied Mathematics')])

Bây giờ, tạo DataFrame và đặt cột đa cấp như trên:

dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],
                         index=['John', 'Tom', 'Henry'],
                         columns=items)

Xếp chồng cột đa cấp:

dataframe.stack()

Ví dụ hoàn chỉnh

Mã nguồn đầy đủ:

import pandas as pd
# cột đa cấp
items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'), ('Maths', 'Applied Mathematics')])
# tạo DataFrame
dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],
                         index=['John', 'Tom', 'Henry'],
                         columns=items)
print("DataFrame...\n", dataFrame)
# xếp chồng cột đa cấp
print("\nStacking...\n", dataFrame.stack())

Kết quả

Chương trình sẽ tạo ra kết quả sau:

DataFrame...
      Maths
  Mental Maths  Discrete Mathematics  Applied Mathematics
John         67                    86                    78
Tom          56                    92                    97
Henry        92                    95                    91
Stacking...
                     Maths
John Applied Mathematics     78
     Discrete Mathematics    86
     Mental Maths            67
Tom  Applied Mathematics     97
     Discrete Mathematics    92
     Mental Maths            56
Henry Applied Mathematics    91
     Discrete Mathematics    95
     Mental Maths            92