如何在 Pandas 中显示列的全文

问题描述

我有一个包含长文本列的数据框。

要演示它的外观(注意文本应继续的省略号“...”):

id  text                       group 
123 My name is Benji and I ... 2

上面的文字实际上比那个短语要长。例如它可以是:

我叫 Benji,住在堪萨斯州。

实际文本比这长得多。

当我尝试仅对文本列进行子集化时,它仅显示带有点“...”的部分文本。

我需要确保显示全文以便稍后进行文本摘要。 但是我不确定在选择文本列时如何显示全文。

我的 df['text'] 输出如下所示:

1    My name is Benji and I ... 
2    He went to the creek and ... 

如何显示全文而不带索引号?

解决方法

您可以将 pd.set_optiony 一起使用来显示自动换行符和多行单元格:

display.max_colwidthint 或 None

pandas 数据结构的 repr 中列的最大字符宽度。当列溢出时,输出中会嵌入一个“...”占位符。 “无”值意味着无限。 [默认值:50]

所以在你的情况下:

display.max_colwidth

对于 older versions,like version 0.22,使用 pd.set_option('display.max_colwidth',None) 而不是 -1

,

您可以将带有换行符 ("\n") 的连接转换为列表:

import pandas as pd

text = """The bullet pierced the window shattering it before missing Danny's head by mere millimeters.
Being unacquainted with the chief raccoon was harming his prospects for promotion.
There were white out conditions in the town; subsequently,the roads were impassable.
The hawk didn’t understand why the ground squirrels didn’t want to be his friend.
Nobody loves a pig wearing lipstick."""

df = pd.DataFrame({"id": list(range(5)),"text": text.splitlines()})

原始输出:

print(df["text"])

产量:

0    The bullet pierced the window shattering it be...
1    Being unacquainted with the chief raccoon was ...
2    There were white out conditions in the town; s...
3    The hawk didn’t understand why the ground squi...
4                 Nobody loves a pig wearing lipstick.

所需的输出:

print("\n".join(df["text"].to_list()))

产量:

The bullet pierced the window shattering it before missing Danny's head by mere millimeters.
Being unacquainted with the chief raccoon was harming his prospects for promotion.
There were white out conditions in the town; subsequently,the roads were impassable.
The hawk didn’t understand why the ground squirrels didn’t want to be his friend.
Nobody loves a pig wearing lipstick.