pandas 如何将3个循环功能组合为1个功能

14ifxucb  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(131)

这是我正在使用的示例数据/脚本。如果可能的话,我尝试在最后一部分使用更少的代码行,以便它看起来更干净/更高效。正如您所看到的,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')
pu82cl6c

pu82cl6c1#

通过列表L添加另一个循环,也使用enumerate(L, 1)作为1的计数,最后使用j变量更改png的生成名称:

L = [df_list1, df_list2, df_list3]

for j, df_list in enumerate(L, 1):
    for i, df in enumerate(df_list):
        styler=(df.style
                  .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']])
        )
        dfi.export(styler, f'test{j}_{i}.png')

编辑:您可以压缩新列表:

L = [df_list1, df_list2, df_list3]
names = ['math', 'biology', 'music']

out = zip(names, L)

for j, (name, df_list) in enumerate(out, 1):
    for i, df in enumerate(df_list):
        styler=(df.style
                  .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']])
        )
        dfi.export(styler,f'{name}_{i}.png')

相关问题