Programmatically convert pandas dataframe to markdown table

后端 未结 13 1278
梦毁少年i
梦毁少年i 2020-12-13 03:44

I have a Pandas Dataframe generated from a database, which has data with mixed encodings. For example:

+----+-------------------------+----------+-----------         


        
13条回答
  •  天命终不由人
    2020-12-13 04:26

    Export a DataFrame to markdown

    I created the following function for exporting a pandas.DataFrame to markdown in Python:

    def df_to_markdown(df, float_format='%.2g'):
        """
        Export a pandas.DataFrame to markdown-formatted text.
        DataFrame should not contain any `|` characters.
        """
        from os import linesep
        return linesep.join([
            '|'.join(df.columns),
            '|'.join(4 * '-' for i in df.columns),
            df.to_csv(sep='|', index=False, header=False, float_format=float_format)
        ]).replace('|', ' | ')
    

    This function may not automatically fix the encoding issues of the OP, but that is a different issue than converting from pandas to markdown.

提交回复
热议问题