【问题标题】:IPython / Jupyter: how to customize the display functionIPython / Jupyter:如何自定义显示功能
【发布时间】:2021-11-24 08:16:56
【问题描述】:

在 IPython / JupyterLab 中显示内容时,我遇到了 3 个基本问题。

(1) 我有一个包含许多列的 pandas 数据框。首先,我确保我能看到它的一部分:

import numpy as np
import pandas as pd
np.set_printoptions(linewidth=240,edgeitems=5,precision=3)
pd.set_option('display.width',1800) #number of pixels of the output
pd.set_option('display.max_columns',100) #replace the number with None to print all columns
pd.set_option('display.max_rows',10) #max_columns/max_rows sets the maximum number of columns/rows displayed when a frame is pretty-printed
pd.set_option('display.min_rows',9) #once max_rows is exceeded, min_rows determines how many rows are shown in the truncated representation
pd.set_option('display.precision',3) #number of digits in the printed float number

如果我打印它,所有东西都会混在一起: enter image description here 是否可以打印文本宽度,即每行(即使更长)仅打印在输出中的 1 行上,当行宽于窗口时使用滑块?

(2) 如果我显示提到的数据框,它看起来非常好(有一个滑块),但是一些字符串条目显示在 4 行上: enter image description here

如何确保每个条目都显示在 1 行中

(3) 下面的代码产生了输出,效果很好:

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0.1,30,1000); 
fig,ax=plt.subplots(1, 4, constrained_layout=True, figsize=[15,2])
ax=ax.ravel()
ax[0].plot( x, np.sin(x))
ax[1].plot( x, np.log(1+x))
ax[2].plot( x, np.sin(30/x))
ax[3].plot( x, np.sin(x)*np.sin(2*x))
plt.show()

enter image description here 但是,当我将[15,2] 更改为[35,2] 时,图形只会与窗口一样宽。我怎样才能实现更大的宽度产生一个滑块(如数据框的显示),以便我可以使图像尽可能宽?

【问题讨论】:

  • 我认为对于 (3),您只需双击图表即可。
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。
  • @JANO 你说得对,双击该图确实解决了我的问题 (3)。谢谢!知道如何按照社区机器人的要求“编辑问题”吗?我的问题不是已经很具体了吗?
  • 不客气!我也试图回答其余的问题。关于您的帖子:我认为您很好,不会被删除。但是,如果您在每个帖子中只包含一个问题/主题,则通常更可取,因为 (3) 与数据框无关。

标签: python dataframe plot jupyter-notebook ipython


【解决方案1】:

您已经通过决定使用 (2) 中的方法显示数据框解决了 (1)。在我看来,使用print 显示数据框并不是很有用。

(2):display(df) 自动使用空格来包装单元格内容。我没有找到禁用此行为的 pandas 选项。幸运的是,其他人已经遇到了同样的问题,并且另一个人提供了 solution

您必须更改数据框的样式属性。为此,您使用Styler,它保存了样式化的数据框。我做了一个简短的示例,您可以从中复制该行:

import pandas as pd

# Construct data frame content
long_text = 'abcabcabc ' * 10
long_row = [long_text for _ in range(45)]
long_table = [long_row for _ in range(15)]

# Create dataframe
df = pd.DataFrame(long_table)


# Select data you want to output
# df_selected = df.head(5) # First five rows
# df_selected = df.tail(5) # Last five rows
df_selected = df.iloc[[1,3, 7]] # Select row 1,3 and 7

# Create styler of df_selected with changed style of white spaces 
dataframe_styler = df_selected.style.applymap(lambda x:'white-space:nowrap')

# Display styler
display(dataframe_styler)

输出:

(3) 正如我在评论中已经提到的,您只需双击图表,它就会显示一个滑块。

【讨论】:

  • 谢谢,现在它适用于小型数据帧。但是,它会显示 所有 行。对于任何更大的数据框,这是不可用的。如何重新开启截断功能?
  • 我不确定样式器需要哪些属性来截断,但我确信有一些方法。但是,我认为限制显示行的最简单解决方案是创建一个仅包含您要显示的数据的缩减数据框。我编辑了答案,只输出数据框的三个特定行。
  • 好的,谢谢你的帮助!
猜你喜欢
  • 2018-07-27
  • 2021-02-23
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 2020-07-17
  • 2020-02-14
  • 2012-06-14
  • 2018-12-27
相关资源
最近更新 更多