Python 如何设置熊猫数据框数据左/右对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17232013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:49:19  来源:igfitidea点击:

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

pythonpandas

提问by bigbug

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().

pd.set_option("display.colheader_justify","right")用来设置列标题。但我找不到数据的选项pd.describe_option()

How to set the data within a dataframe display left or right alignment for each column? Or, is it possible to define a format template for the whole row data display?

如何设置数据框中的数据显示每列的左对齐或右对齐?或者,是否可以为整行数据显示定义格式模板?

回答by Romain

If you want to change the display in a Jupyter Notebook, you can use the Stylefeature.

如果要更改 Jupyter Notebook 中的显示,可以使用样式功能。

# Test data
df = DataFrame({'text': ['foo', 'bar'],
                 'number': [1, 2]})

df.style.set_properties(**{'text-align': 'right'})

enter image description here

在此处输入图片说明

回答by mozlingyu

you can control it by a new context:

你可以通过一个新的上下文来控制它:

with pd.option_context('display.colheader_justify','right'):
    ...

回答by JS.

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.

在我的情况下,我的 Pandas DataFrame 有一个类包装器。这允许我通过自定义包装器的__str__()方法来左对齐 DataFrame 的字符串输出。

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

根据Unutbu类似问题的回答,这是我为我的应用程序解决问题的方法。Pandas DataFrame 被引用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)

回答by Hagbard

The answer given by @Romainis great but I would like to summarize some comments:

@Romain给出的答案很棒,但我想总结一些评论:

# Test data
df = DataFrame({'text': ['foo', 'bar'],'number': [1, 2]})

dfStyler = df.style.set_properties(**{'text-align': 'left'})
dfStyler.set_table_styles([dict(selector='th', props=[('text-align', 'left')])])

will align all table text andthe column headers as well.

也会对齐所有表格文本列标题。

回答by Federico Gentile

If you wanna align both text and header to the left for example you can use:

例如,如果您想将文本和标题都向左对齐,您可以使用:

df.style.set_properties(**{'text-align': 'left'}).set_table_styles([ dict(selector='th', props=[('text-align', 'left')] ) ])

This first sets the text to the left and then the header.

这首先将文本设置为左侧,然后设置标题。