我想用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'])
有什么想法吗?你知道吗
考虑
pivot_table
与一些没有任何循环的列名争用。你知道吗数据
处理(扩展15个列组中每个列的透视值和货币)
相关问题 更多 >
编程相关推荐