如何用Python Pandas调整CSV转HTML时的列输出顺序
如何调整Pandas导出HTML时的列顺序
我编写了一段Python脚本,借助Pandas读取CSV格式的TXT文件并将其转换为HTML文件。希望调整输出到HTML文件中的列顺序,但不清楚该在读取阶段还是写入阶段进行操作,也不知道应使用什么函数。
原代码如下:
import pandas as pd import os import shutil import glob # paths HTMLPATH="C:/NMS4/QUE/HTML/" QUEPATH="C:/NMS4/QUE/" # create the directory for holding the HTML files if it doesn't exist isExist = os.path.exists(HTMLPATH) if not isExist: os.mkdir(HTMLPATH, 0o777) # convert .txt file to a html file in the HTML folder # can't convert an empty file so only convert if file size in not 0 for quefile in glob.iglob('C:/NMS4/QUE/*.txt'): if os.path.getsize(quefile) != 0: csv = pd.read_csv(quefile, header=None, usecols=[0,3,4,15,34,43,44,129], names=['OrderNo','Req Qty','Planned Start','Resource','Op','Part','Desc','Qty Recd']) html_table = csv.to_html() f = open(quefile + '.html', 'w') f.write(html_table) f.close() shutil.move(quefile + ".HTML", HTMLPATH)
查阅相关文档后没找到to_html直接调整列顺序的参数,后来自己修改出了解决方案,不过其实可以用更简洁的方式实现:直接通过指定列名列表重新排列DataFrame的列,无需手动交换索引。
优化后的代码如下:
import pandas as pd import os import shutil import glob # paths HTMLPATH="C:/NMS4/QUE/HTML/" QUEPATH="C:/NMS4/QUE/" # create the directory for holding the HTML files if it doesn't exist isExist = os.path.exists(HTMLPATH) if not isExist: os.mkdir(HTMLPATH, 0o777) # convert .txt file to a html file in the HTML folder # python can't convert an empty file so only convert if file size in not 0 for quefile in glob.iglob('C:/NMS4/QUE/*.txt'): if os.path.getsize(quefile) != 0: csv = pd.read_csv(quefile, header=None, usecols=[0,3,4,15,34,43,44,129], names=['Order No','Req Qty','Planned Start','Resource','Op','Part','Desc','Qty Recd']) # 直接指定想要的列顺序 desired_cols = ['Order No', 'Op', 'Part', 'Desc', 'Planned Start', 'Req Qty', 'Resource', 'Qty Recd'] df = csv[desired_cols] html_table = df.to_html() f = open(quefile + '.html', 'w') f.write(html_table) f.close() shutil.move(quefile + ".HTML", HTMLPATH)
说明
- 调整列顺序的操作应该在读取文件之后、导出HTML之前完成,也就是对DataFrame进行列重排后再调用
to_html()。 - 直接传入目标列名列表是最直观高效的方式,比手动交换索引更易读也更易维护。
内容的提问来源于stack exchange,提问作者tt_time
相关产品推荐
相关产品推荐

