Home > Net >  How to create multiple png files using styler function
How to create multiple png files using styler function

Time:12-12

Below is the example script/data I am working with. When trying to create multiple png files using a list, test = [], running this script gives me this error OSError: [Errno 22] Invalid argument: 'test<pandas.io.formats.style.Styler object at 0x0000025FD890D250>.png'. I think the error is coming from the last loop, how would I change this, dfi.export(df, f'test{i}.png') or any other suggestions to output all the data frames in the list would be great.

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_list=[df,df2]

def colors(i):
    if i > 0:
        return 'background: red'
    elif i < 0:
        return 'background: green'
    elif i == 0:
        return 'background: yellow'
    else:
        ''

test=[]
for df in df_list:
    filename=(df.style
        .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice[:,'a']])
    )
    test.append (filename)
    
    for df in test:
        dfi.export(df, f'test{i}.png')

CodePudding user response:

If need numeric suffix in new filenames of png like test0 and test1 here use:

for i, df in enumerate(test):
    dfi.export(df, f'test{i}.png')

Another solution without another loop:

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