这是我正在使用的示例数据/脚本。如果可能的话,我尝试在最后一部分使用更少的代码行,以便它看起来更干净/更高效。正如您所看到的,for i, df in enumerate(df_list1): styler=(df.style .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']]) ) dfi.export(styler, f'test1_{i}.png')
使用不同的列表名称df_list2和df_list3重复了两次以上。我如何将三个循环函数组合成一个循环函数?任何帮助都将非常感谢。
import pandas as pd
import dataframe_image as dfi
df = pd.DataFrame(data=[[-100,500,400,0,222,222], [9000,124,0,-147,54,-56],[77,0,110,211,0,222], [111,11,-600,33,0,22],[213,-124,0,-147,54,-56]])
df2 = pd.DataFrame(data=[[100,500,200,0,555,222], [5000,124,0,-147,54,50],[77,0,500,211,0,222], [-900,11,-600,33,0,22],[500,-124,0,-147,54,-56]])
df.columns = pd.MultiIndex.from_product([['x','y','z'], list('ab')])
df2.columns = pd.MultiIndex.from_product([['x','y','z'], list('ab')])
df_list1=[df]
df_list2=[df2]
df_list3=[df,df2]
def colors(i):
if i < 0:
return 'background: red'
elif i > 0:
return 'background: green'
elif i == 0:
return 'background: yellow'
else:
''
for i, df in enumerate(df_list1):
styler=(df.style
.applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']])
)
dfi.export(styler, f'test1_{i}.png')
for i, df in enumerate(df_list2):
styler=(df.style
.applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']])
)
dfi.export(styler, f'test2_{i}.png')
for i, df in enumerate(df_list3):
styler=(df.style
.applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']])
)
dfi.export(styler, f'test3_{i}.png')
1条答案
按热度按时间pu82cl6c1#
通过列表
L
添加另一个循环,也使用enumerate(L, 1)
作为1
的计数,最后使用j
变量更改png
的生成名称:编辑:您可以压缩新列表: