用Pandas重新格式化Excel文件

2024-05-19 07:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Pandas重新格式化Excel文件。你知道吗

Excel文件包含一个ID列表,在不同的日期和不同的机器上对其执行多个操作。这些数据是按操作记录的,我想按ID重新格式化它们

我做的代码(简化)工作得很好,但实际上效率不高。在我真正的15列x 20 000行~16Mb的Excel文件中,需要~2/3h才能运行。。。你知道吗

# -*- coding: utf-8 -*-

import pandas as pd
from collections import OrderedDict

data = pd.read_excel('Exemple.xlsx')

IDlist = data.ID.unique().tolist()
for ID in IDlist:

    tempData = OrderedDict()
    tempData['ID'] = ID
    for OP in data[data['ID'] == ID]['Operation'].tolist():

        tempData[str(OP)+'_Date'] = data[data['ID'] == ID][data['Operation'] == OP]['Date'].iloc[0].date()
        tempData[str(OP)+'_Machine'] = data[data['ID'] == ID][data['Operation'] == OP]['Machine'].iloc[0]

    if 'outputData' not in locals():
        outputData = pd.DataFrame(tempData, index=[0])
    else:
        outputData = outputData.append(tempData, ignore_index=True)

writer = pd.ExcelWriter('outputExemple.xlsx')
outputData.to_excel(writer,'sheet',index=False)
writer.save()

你知道吗示例.xlsx是这样的(作为csv,因为它将更易于您导入):

ID;Operation;Date;Machine
ID1;10;05/01/2018;Machine1
ID1;20;06/01/2018;Machine2
ID1;30;10/01/2018;Machine3
ID1;40;11/01/2018;Machine4
ID1;50;12/01/2018;Machine5
ID2;10;10/01/2018;Machine1
ID2;20;14/01/2018;Machine2
ID2;30;17/01/2018;Machine3
ID2;50;20/01/2018;Machine5
ID3;10;15/01/2018;Machine1
ID3;30;16/01/2018;Machine3
ID3;50;17/01/2018;Machine5

你知道吗输出示例.xlsx-按ID排序(仍为csv…)

ID;10_Date;10_Machine;20_Date;20_Machine;30_Date;30_Machine;40_Date;40_Machine;50_Date;50_Machine
ID1;2018-01-05;Machine1;2018-01-06;Machine2;2018-01-10;Machine3;2018-01-11;Machine4;2018-01-12;Machine5
ID2;2018-01-10;Machine1;2018-01-14;Machine2;2018-01-17;Machine3;;;2018-01-20;Machine5
ID3;2018-01-15;Machine1;;;2018-01-16;Machine3;;;2018-01-17;Machine5

为了加快速度,我建议使用双索引,因为“ID”和“Operation”的组合是唯一的。但我没办法,我不知道这是否真的能让它更快。。。你知道吗

data = data.set_index(['ID', 'Operation'])

有什么想法吗?你知道吗


Tags: iddatadatemachinexlsxoperationpdid2
1条回答
网友
1楼 · 发布于 2024-05-19 07:21:34

考虑pivot_table与一些没有任何循环的列名争用。你知道吗

数据

from io import StringIO
import pandas as pd

txt = '''ID;Operation;Date;Machine
ID1;10;05/01/2018;Machine1
ID1;20;06/01/2018;Machine2
ID1;30;10/01/2018;Machine3
ID1;40;11/01/2018;Machine4
ID1;50;12/01/2018;Machine5
ID2;10;10/01/2018;Machine1
ID2;20;14/01/2018;Machine2
ID2;30;17/01/2018;Machine3
ID2;50;20/01/2018;Machine5
ID3;10;15/01/2018;Machine1
ID3;30;16/01/2018;Machine3
ID3;50;17/01/2018;Machine5'''

df = pd.read_table(StringIO(txt), sep=";", parse_dates=[2], dayfirst=True)

处理(扩展15个列组中每个列的透视值和货币)

pvt_df = df.pivot_table(index='ID', columns=['Operation'], 
                        values=['Date', 'Machine'], aggfunc='max')    
print(pvt_df)
#                 Date                                               Machine                                        
# Operation         10         20         30         40         50        10        20        30        40        50
# ID                                                                                                                
# ID1       2018-01-05 2018-01-06 2018-01-10 2018-01-11 2018-01-12  Machine1  Machine2  Machine3  Machine4  Machine5
# ID2       2018-01-10 2018-01-14 2018-01-17        NaT 2018-01-20  Machine1  Machine2  Machine3      None  Machine5
# ID3       2018-01-15        NaT 2018-01-16        NaT 2018-01-17  Machine1      None  Machine3      None  Machine5

# COLUMN WRANGLING
currcols = [o+'_Date' for o in pvt_df.columns.levels[1].astype('str')] + \
           [m+'_Machine' for m in pvt_df.columns.levels[1].astype('str')] 

# FLATTEN HIERARCHY
pvt_df.columns = pvt_df.columns.get_level_values(0)

# ASSIGN COLUMNS
pvt_df.columns = currcols

# RE-ORDER COLUMNS
pvt_df = pvt_df[sorted(currcols)]

# OUTPUT SEMI-COLON DELIMITED CSV
pvt_df.to_csv('Output.csv', sep=";")

# ID;10_Date;10_Machine;20_Date;20_Machine;30_Date;30_Machine;40_Date;40_Machine;50_Date;50_Machine
# ID1;2018-01-05;Machine1;2018-01-06;Machine2;2018-01-10;Machine3;2018-01-11;Machine4;2018-01-12;Machine5
# ID2;2018-01-10;Machine1;2018-01-14;Machine2;2018-01-17;Machine3;;;2018-01-20;Machine5
# ID3;2018-01-15;Machine1;;;2018-01-16;Machine3;;;2018-01-17;Machine5

相关问题 更多 >

    热门问题