How to save the Pandas dataframe/series data as a figure?

前端 未结 7 1805
猫巷女王i
猫巷女王i 2020-11-29 00:25

It sounds somewhat weird, but I need to save the Pandas console output string to png pics. For example:

>>> df
                   sales  net_pft             


        
7条回答
  •  野性不改
    2020-11-29 00:58

    I had the same requirement for a project I am doing. But none of the answers were elegant per my requirement. Here is something which finally helped me, and might be useful for this case, using Bokeh:

    from bokeh.io import export_png, export_svgs
    from bokeh.models import ColumnDataSource, DataTable, TableColumn
    
    def save_df_as_image(df, path):
        source = ColumnDataSource(df)
        df_columns = [df.index.name]
        df_columns.extend(df.columns.values)
        columns_for_table=[]
        for column in df_columns:
            columns_for_table.append(TableColumn(field=column, title=column))
    
        data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
        export_png(data_table, filename = path)
    

    Sample output:

提交回复
热议问题