将具有多个标头的DataFrame融合为标准化格式

问题描述 投票:0回答:1

我有这样的Excel数据。我想在将其转换为规范化格式后将其插入RDB。第一个标题表示日期,第二个标题表示某个类别或类型。值表示每种类型的计数。

Origin

所以输出格式看起来像这样。

Target

我可以通过以下代码将原始数据读入DataFrame,但似乎没有一种简单的方法来展开具有多个标头的DataFrame。

df = pd.read_excel('original_data.xlsx', header=[1,2])

我试过this solution,但似乎没有正常工作。

是否有任何魔法来处理此数据透视表?

python python-3.x pandas dataframe pivot-table
1个回答
1
投票

我重新创建了你的数据(下次提供数据而不是图像)并做了这样的事情:

import pandas as pd
# Read the file
df = pd.read_excel(r'Data/Stackoverflow_04_25.xlsx',  header=[0,1])
# 'break' the levels in the colum names
df.columns = ['_'.join(col)for col in df.columns]
# Rename some of the columns
df = df.rename(columns = {'ID_Unnamed: 0_level_1':'ID','COUNTRY _Unnamed: 1_level_1':'Country','NAME_Unnamed: 2_level_1':'Name'})
# Generate a new 'final' dataframe
df_ = pd.DataFrame(columns = ['ID', 'Country', 'Name'])
# loop over the columns of interes an add the result to the final df
for column in ['4/1_Type2', '4/1_Type3' ,   '4/2_Type1',    '4/2_Type2' ,'4/2_Type3']:
    df1 = df.groupby(['ID', 'Country', 'Name'], as_index = False)[column].first().rename(columns = {column:'Counts'})
    df1.loc[:,'Date'] = column[:3]
    df1.loc[:,'Type'] = column[-5:]
    df_ = pd.concat([df_, df1], 0, sort = True).reset_index(drop = True)
# Order the final dataframe columns
df_ = df_[['ID', 'Country', 'Name', 'Type', 'Date', 'Counts']]
df_

这看起来非常类似于你想要的。希望这有效。

    ID  Country Name    Type    Date    Counts
0   1   A   D   Type2   4/1 0.0
1   2   B   E   Type2   4/1 0.0
2   3   C   F   Type2   4/1 5.0
3   1   A   D   Type3   4/1 10.0
4   2   B   E   Type3   4/1 5.0
5   3   C   F   Type3   4/1 15.0
6   1   A   D   Type1   4/2 10.0
7   2   B   E   Type1   4/2 10.0
8   3   C   F   Type1   4/2 10.0
9   1   A   D   Type2   4/2 0.0
10  2   B   E   Type2   4/2 10.0
11  3   C   F   Type2   4/2 10.0
12  1   A   D   Type3   4/2 0.0
13  2   B   E   Type3   4/2 0.0
14  3   C   F   Type3   4/2 10.0
© www.soinside.com 2019 - 2024. All rights reserved.