【发布时间】:2021-02-24 11:37:52
【问题描述】:
我有带有多头的 Pandas 数据帧,我只在循环中的几列上应用条件格式(例如,6、7、9、10、12、13...)我已经用于循环,如下所示:
for i in range(6,len(df1.columns),3):
print(i)
worksheet.conditional_format(4,int(i),len(df1)+3,int(i+1), {'type': 'cell', \
'criteria': '>=', \
'value':'45',\
'format': format1
})
这会使我的 Excel 输出损坏,而且如果我修复 Excel,我可以看到我的标题移动了 1 个单元格。此外,该 Excel 中没有进行条件格式设置。任何人都可以帮助解决这个问题吗? 此外,如果我从代码输出中删除这一行很好,但没有条件格式。
这里是示例代码:
import pandas as pd
th='30000'
cars = {'day':['aug','aug','sep','sep','aug'],
'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4','Hyundai Elite i20'],
'Type':['sedan,','sedan','hatchback','hatchback','hatchback'],
'Down Price': [22000,25000,27000,35000,10000]
}
df = pd.DataFrame(cars, columns = ['day','Brand', 'Type','Down Price'])
dfpivot=pd.pivot_table(df,index=['day'],columns=['Brand','Type'],values=['Down Price'],aggfunc=np.max)
with pd.ExcelWriter(OUTPATH+'Report.xlsx', engine='xlsxwriter') as writer:
dfpivot.to_excel(writer,sheet_name = 'data')
workbook = writer.book
worksheet = writer.sheets['data']
format1 = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
for i in range(1,len(dfpivot.columns),1):
print(i)
worksheet.conditional_format(4,int(i),len(df1)+3,int(i+1), {'type': 'cell', \
'criteria': '>=', \
'value':th,\
'format': format1
})
writer.save()
【问题讨论】:
-
请提供一个可重现的例子:stackoverflow.com/help/minimal-reproducible-example 这意味着我们必须能够复制您的代码,在我们的机器上运行它并遇到您面临的相同问题
标签: pandas conditional-formatting xlsxwriter