pandas pivot_table pivot table, MultiIndex multi-level index creation

Reference:
https://blog.csdn.net/ljr_123/article/details/115250639

1. pivot_table pivot table

import pandas as pd

# 创建示例数据
data = {
    'Year': [2019, 2019, 2020, 2020, 2019, 2019, 2020, 2020],
    'Quarter': ['Q1', 'Q2', 'Q1', 'Q2', 'Q1', 'Q2', 'Q1', 'Q2'],
    'Product': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
    'Sales': [100, 150, 200, 250, 120, 180, 220, 280]
}

df = pd.DataFrame(data)

# 使用 pivot_table 创建透视表,并指定多级列索引
pivot = df.pivot_table(values='Sales', index='Year', columns=['Quarter', 'Product'], aggfunc='sum')

print(pivot)

pivot.to_excel('test.xlsx')

Saving in xlsx format will not merge; saving in csv format will not work properly
Insert image description here

2. MultiIndex multi-level index creation

import pandas as pd

# 定义示例数据
data = {
    ('Year', ''): [2019, 2019, 2020, 2020],
    ('Quarter', ''): ['Q1', 'Q2', 'Q1', 'Q2'],
    ('Sales', 'Product A'): [100, 150, 200, 250],
    ('Sales', 'Product B'): [120, 180, 220, 280]
}

# 创建 MultiIndex 对象
columns = pd.MultiIndex.from_tuples(data.keys())

# 创建带有多级索引的 DataFrame
df = pd.DataFrame(data.values(), columns=columns)

print(df)


df.to_excel('test1.xlsx')

Insert image description here

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42357472/article/details/131930965