我有一个Pandas数据帧,在转置后有2列。如果我导出到Excel,第一列会出现格式,xlsxwriter无法控制(所有其他列都可以格式化)。如果我尝试在索引0处的Pandas数据框中插入一个新列,它将在索引1处进入。为什么第一个数据帧列在Pandas中不可更改且无法由xlsxwriter格式化?
这是我的原始代码:
data_xls = pandas.read_excel(excelPath, "FlowTimes", index_col=None)
del data_xls['OBJECTID'] #Remove OBJECTID column
del data_xls['Shape_Length'] #Remove the Shape_Length column
data_xls.drop(data_xls.columns[0], axis =1) #Remove nameless first column
decimals = pandas.Series([0,2,0,2,0,2,0,2], index=['Length FT', 'Length MI','Flow Minutes - Mean Annual','Flow Hours - Mean Annual')
data_xls2 = data_xls.round(decimals)
data_export = data_xls2.transpose() #Transpose columns to rows
data_export.reset_index()
data_export.insert(0,"Temp", None) #THIS IS A TESTING LINE TO SEE WHERE THE COLUMN INSERTS - IT SHOULD INSERT AS THE FIRST COLUMN AT INDEX 0
print data_export
os.remove(excelPath)
writer = pandas.ExcelWriter(excelPath + "x")
data_export.to_excel(writer, sheet_name = 'FlowTimes', startcol = 0, startrow = 0, header=False) #header = false removes the 0 index in the first row
workbook = writer.book
worksheet = writer.sheets['FlowTimes']
format1 = workbook.add_format()
format1.set_align('right')
format1.set_border(0)
format2 = workbook.add_format()
format2.set_bold()
worksheet.set_column("A:A", 30, format1)
worksheet.set_column("B:Z", 12, format1)
worksheet.set_row(0,None, format2)
writer.save()
如果我没有包含data_export.insert列进行测试,则输出如下所示:
0
Key Strategy Location Location A
Length FT 3551
Length MI 0.67
Flow Minutes - Mean Annual 35
Flow Hours - Mean Annual 0.58
但是如果我在索引0处包含data_export.insert列,它会在第一列之后插入,如下所示:
Temp 0
Key Strategy Location None Location A
Length FT None 3551
Length MI None 0.67
Flow Minutes - Mean Annual None 35
Flow Hours - Mean Annual None 0.58
如何在使用xlsxwriter导出时,在索引0处插入新列或控制第一列的格式?
答案 0 :(得分:1)
事实证明,xlsxwriter使用无法更改的格式导入pandas索引(行名称)。我通过将索引复制到第一列,然后导出到没有标题或索引的Excel来解决这个问题。现在,所有列和行的xlsxwriter格式都可以使用。这是工作代码:
Function