pandas 如何使用styler函数创建多个png文件

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

下面是我正在使用的示例脚本/数据。当尝试使用列表test = []创建多个png文件时,运行此脚本会给我错误OSError: [Errno 22] Invalid argument: 'test<pandas.io.formats.style.Styler object at 0x0000025FD890D250>.png'。我认为错误来自最后一个循环dfi.export(df, f'test{i}.png')。任何输出列表中所有 Dataframe 的建议都很好。

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')
rdlzhqv9

rdlzhqv91#

如果png的新文件名(如test0test1)需要数字后缀,请用途:

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

另一种解决方案,无需另一个循环:

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')

相关问题