如何在IPython笔记本中的pandas DataFrame列中保留对齐文本

Fre*_*ell 9 ipython pandas ipython-notebook

我试图在IPython笔记本中格式化输出.我尝试使用to_string函数,这巧妙地让我删除了索引列.但文本数据是正确的.

在[10]中:

import pandas as pd
columns = ['Text', 'Value']
a = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print (a.to_string (index=False))

   Text  Value
 abcdef  12.34
      x   4.20
Run Code Online (Sandbox Code Playgroud)

仅打印数据帧时也是如此.

在[12]中:

print (a)

     Text  Value
0  abcdef  12.34
1       x   4.20
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,to_string函数中的justify参数只能证明列标题的合理性.

在[13]中:

import pandas as pd
columns = ['Text', 'Value']
a = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print (a.to_string (justify='left', index=False))
Text     Value
 abcdef  12.34
      x   4.20
Run Code Online (Sandbox Code Playgroud)

如何控制各列的对齐设置?

unu*_*tbu 10

您可以使用在左对齐格式化程序中a['Text'].str.len().max()计算最长字符串的长度a['Text'],并使用该数字:N'{:<Ns}'.format

In [211]: print(a.to_string(formatters={'Text':'{{:<{}s}}'.format(a['Text'].str.len().max()).format}, index=False))
   Text  Value
 abcdef  12.34
 x        4.20
Run Code Online (Sandbox Code Playgroud)

  • 这就是我想要的 - 谢谢.但它仍然非常冗长.我认为应该有一个更简单的方法. (4认同)

Bri*_*rns 8

如果你愿意使用另一个图书馆,表格会这样做 -

$ pip install tabulate
Run Code Online (Sandbox Code Playgroud)

然后

from tabulate import tabulate
df = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print(tabulate(df, showindex=False, headers=df.columns))

Text      Value
------  -------
abcdef    12.34
x          4.2
Run Code Online (Sandbox Code Playgroud)

它还有各种其他输出格式.


Ral*_*lph 7

我喜欢@unutbu的答案(不需要任何额外的依赖项)。@JS. 的添加是朝这个方向迈出的一步(朝向可重用的东西)。

由于格式化程序字典的构造是困难的部分,因此让我们创建一个函数,该函数从 DataFrame 和要格式化的可选列列表创建格式化程序字典。

def make_lalign_formatter(df, cols=None):
    """
    Construct formatter dict to left-align columns.

    Parameters
    ----------
    df : pandas.core.frame.DataFrame
        The DataFrame to format
    cols : None or iterable of strings, optional
        The columns of df to left-align. The default, cols=None, will
        left-align all the columns of dtype object

    Returns
    -------
    dict
        Formatter dictionary

    """
    if cols is None:
       cols = df.columns[df.dtypes == 'object'] 

    return {col: f'{{:<{df[col].str.len().max()}s}}'.format for col in cols}
Run Code Online (Sandbox Code Playgroud)

让我们创建一些示例数据来演示如何使用此函数:

import pandas as pd

# Make some data
data = {'First': ['Tom', 'Dick', 'Harry'],
        'Last': ['Thumb', 'Whittington', 'Potter'],
        'Age': [183, 667, 23]}

# Make into a DataFrame
df = pd.DataFrame(data)
Run Code Online (Sandbox Code Playgroud)

要对齐DataFrame 中对象类型的所有列:

# Left align all columns
print(df.to_string(formatters=make_lalign_formatter(df), 
                   index=False,
                   justify='left'))
Run Code Online (Sandbox Code Playgroud)

对齐列'First'

# Left align 'First' column
print(df.to_string(formatters=make_lalign_formatter(df, cols=['First']), 
                   index=False,
                   justify='left'))
Run Code Online (Sandbox Code Playgroud)