使用数据透视表拆分列

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

我需要在Python中将行拆分或分解为列的功能是什么?我需要我的数据:

AreaCode | Type        | Disag    | Value 
101      | Numerator   | Total    | 10
101      | Denominator | Total    | 20
102      | Numerator   | Total    | 55
102      | Denominator | Total    | 65

到此4列表:

AreaCode | Disag | Denominator | Numerator  
101      | Total | 10          | 20
102      | Total | 55          | 65

这是导入第一个表的代码:

import pandas as pd

raw_data = {'AreaCode' : ['101', '101', '102', '102'],
            'Type' : ['Numerator', 'Denominator', 'Numerator', 'Denominator'],
            'Disag' : ['Total', 'Total', 'Total', 'Total'],
            'Value' : [10, 20, 55, 65]}

Data = pd.DataFrame(raw_data, columns = ['AreaCode', 'Type', 'Disag', 'Value'])

我如何使它看起来像我想要的?到目前为止,我所能想到的就是:

Data = Data.pivot_table(values = 'Value',
                        index = ['AreaCode', 'Disag'],
                        columns = 'Type')

这将创建一个只有两列(分子和分母)以及一些索引的表。请帮助!

python pivot-table
1个回答
0
投票

您可以做:

Data = Data.pivot_table(index='AreaCode', columns=['Type', 'Disag']).stack(level='Disag')
Data.columns = Data.columns.get_level_values(1)
print(Data.reset_index())

要打印:

Type AreaCode  Disag  Denominator  Numerator
0         101  Total           20         10
1         102  Total           65         55

编辑:要保存为CSV,您可以执行以下操作:

Data = Data.pivot_table(index='AreaCode', columns=['Type', 'Disag']).stack(level='Disag')
Data.columns = Data.columns.get_level_values(1)
Data = Data.reset_index()

Data.to_csv('data.csv', index=False)  # <-- save it to CSV

这将像这样保存到CSV:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.