如何在 IPython 笔记本的 Pandas DataFrame 列中左对齐文本 [英] How can I left justify text in a pandas DataFrame column in an IPython notebook

查看:33
本文介绍了如何在 IPython 笔记本的 Pandas DataFrame 列中左对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 right justified.

在 [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

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

The same is true when just printing the dataframe.

在 [12] 中:

print (a)

     Text  Value
0  abcdef  12.34
1       x   4.20

令人惊讶的是,to_string 函数中的 justify 参数仅对齐列标题.

The justify argument in the to_string function, surprisingly, only justifies the column heading.

在 [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

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

How can I control the justification settings for individual columns?

推荐答案

如果您愿意使用其他库,制表 会这样做 -

If you're willing to use another library, tabulate will do this -

$ pip install tabulate

然后

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

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

It has various other output formats also.

这篇关于如何在 IPython 笔记本的 Pandas DataFrame 列中左对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆