use*_*609 16 python ipython pandas
我在Jupyter Notebook中查看Pandas DataFrame,我的DataFrame包含URL请求字符串,可以是数百个字符长,没有任何空格分隔字符.
当有空白时,Pandas似乎只在文本中包装文本,如附图所示:
如果没有空格,则字符串显示在一行中,如果没有足够的空间,我的选项要么是要看'...',要么我必须设置display.max_colwidth
为一个巨大的数字,现在我有一个难以阅读的表格,滚动很多.
有没有办法强制Pandas包装文本,比如每100个字符,无论是否有空格?
您可以使用str.wrap
方法:
df['user_agent'] = df['user_agent'].str.wrap(100) #to set max line width of 100
Run Code Online (Sandbox Code Playgroud)
You can set
import pandas as pd
pd.set_option('display.max_colwidth', 0)
Run Code Online (Sandbox Code Playgroud)
and then each column will be just as big as it needs to be in order to fully display it's content. It will not wrap the text content of the cells though (unless they contain spaces).
首先尝试将文本换行,然后执行下面的函数。得票最高的答案并不能有效地换行文本。
通过使用pd.set_option('display.max_colwidth', 0)
,它会无效地换行文本,如下所示:
但是,通过使用以下代码,它将有效地将文本换行到任何列宽度:
from IPython.display import display, HTML
def wrap_df_text(df):
return display(HTML(df.to_html().replace("\\n","<br>")))
df['user_agent'] = df['user_agent'].str.wrap(30)
wrap_df_text(df)
display(df)
Run Code Online (Sandbox Code Playgroud)
如果您不介意在将整个数据放入数据框中之前解决这个问题,您可以按照此处所述进行操作。在您的特定情况下,如果您希望每行长度为 10 个字符,则需要:
# Input
line = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0; GomezAgent 3.0)
like Gecko'
n = 10
# Split
line = [line[i:i+n] for i in range(0, len(line), n)]
# The rest is easy
df = pd.DataFrame(line)
print(df)
Run Code Online (Sandbox Code Playgroud)
没有空格,您将得到:
顺便说一句,最后一行开头出现空白是因为没有 10 个字符来填充该行,就像前面的行一样。在 jupyter 中,您可以通过使用以下方法来解决此问题df.style.set_properties(**{'text-align': 'left'})
:
归档时间: |
|
查看次数: |
5984 次 |
最近记录: |