How can I left justify text in a pandas DataFrame column in an IPython notebook

后端 未结 4 1510
太阳男子
太阳男子 2020-12-16 14:21

I am trying to format the output in an IPython notebook. I tried using the to_string function, and this neatly lets me eliminate the index column. But the textual data is ri

4条回答
  •  情书的邮戳
    2020-12-16 15:08

    This works on Python 3.7 (functools is a part of that release now)

    # pylint: disable=C0103,C0200,R0205
    from __future__ import print_function
    import pandas as pd
    import functools
    
    @staticmethod
    def displayDataFrame(dataframe, displayNumRows=True, displayIndex=True, leftJustify=True):
        # type: (pd.DataFrame, bool, bool, bool) -> None
        """
        :param dataframe: pandas DataFrame
        :param displayNumRows: If True, show the number or rows in the output.
        :param displayIndex: If True, then show the indexes
        :param leftJustify: If True, then use technique to format columns left justified.
        :return: None
        """
    
        if leftJustify:
            formatters = {}
    
            for columnName in list(dataframe.columns):
                columnType = type(columnName)  # The magic!!
                # print("{} =>  {}".format(columnName, columnType))
                if columnType == type(bool):
                    form = "{{!s:<8}}".format()
                elif columnType == type(float):
                    form = "{{!s:<5}}".format()
                else:
                    max = dataframe[columnName].str.len().max()
                    form = "{{:<{}s}}".format(max)
    
                formatters[columnName] = functools.partial(str.format, form)
    
            print(dataframe.to_string(index=displayIndex, formatters=formatters), end="\n\n")
        else:
            print(dataframe.to_string(index=displayIndex), end="\n\n")
    
        if displayNumRows:
            print("Num Rows: {}".format(len(dataframe)), end="\n\n")
    

提交回复
热议问题