如何在Pandas中显示一列的完整文本

5

我有一个数据框,其中包含一列长文本。

为了演示它的样子(请注意省略号“...”,表示文本应该继续):

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

上述文本实际上比那个短语要长。例如,它可能是:
“我的名字叫本吉,我住在堪萨斯。”
实际文本比这个要长得多。
当我尝试仅对文本列进行子集操作时,它只显示带有省略号“...”的部分文本。
我需要确保在后续的文本摘要中显示完整的文本。
但我不确定如何在选择文本列时显示完整的文本。
我的df['text']输出看起来像这样:
1    My name is Benji and I ... 
2    He went to the creek and ... 

如何显示完整文本并去除索引号?

1
你使用了什么代码来生成这个输出? - Scott Hunter
只需要一个简单的 df['text'],这样我就可以将其分配为变量“sentence”。 - user15851936
https://dev59.com/210a5IYBdhLWcg3w07kt - domandinho
有没有办法不打印索引号? - user15851936
https://dev59.com/AWAf5IYBdhLWcg3wcyar - domandinho
print(df.to_string(index=False)) - domandinho
3个回答

11
您可以使用 pd.set_option 来设置 display.max_colwidth,从而显示自动换行和多行单元格:

display.max_colwidth int 或 None

在 pandas 数据结构的 repr 中,列的最大宽度(以字符为单位)。当列溢出时,会在输出中嵌入 “…” 占位符。'None' 值表示无限制。[默认值:50]

所以,在您的情况下:

pd.set_option('display.max_colwidth', None)

对于旧版本,如0.22版,请使用 -1 而不是 None

此答案解决了显示问题,同时不修改数据本身。 - hc_dev
3
你可以使用上下文(context)来仅在需要时而非全局应用此显示选项,例如:with pd.option_context("display.max_colwidth", None): ... - Rafs

2
你可以将其转换为列表,然后使用换行符("\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.

实际上,你甚至不需要使用 to_list()print("\n".join(df["text"])) 的效果是一样的。 - cosmic_inquiry

0
dataframe.head(1)['columnname'].values

您的答案可以通过添加进一步细节(例如引用或文档)来改善。请编辑以添加更多详细信息,以便其他人可以确认您的答案是否正确。您可以在帮助中心中找到有关编写良好答案的更多信息。 - moken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接