How to set the pandas dataframe data left/right alignment?

后端 未结 6 990
礼貌的吻别
礼貌的吻别 2020-11-30 05:23

I use pd.set_option(\"display.colheader_justify\",\"right\") to set the column header. But I can\'t find the option for data by pd.describe_option()

6条回答
  •  甜味超标
    2020-11-30 06:10

    In my situation, I have a class wrapper around my Pandas DataFrame. This allows me to left-justify the DataFrame's string output by customizing the wrapper's __str__() method.

    Here's how I solved the problem for my application, based on Unutbu's answer to a similar question. The Pandas DataFrame is referenced by self.data:

    def __str__(self):
        """
        Return the test stats report as a single string
        with left-justified columns.
    
        """
        # Columns containing boolean values need different format strings
        # to avoid 'ValueError: Invalid format specifier' exceptions.
        BOOL_COLUMNS = ['success',]
    
        formatters = {}
        for li in list(self.data.columns):
            if li in BOOL_COLUMNS:
                form = "{{!s:<5}}".format()
            else:
                max = self.data[li].str.len().max()
                form = "{{:<{}s}}".format(max)
    
            formatters[li] = functools.partial(str.format,form)
    
        return self.data.to_string(formatters=formatters, index=False)
    

提交回复
热议问题