跳转到主要内容

用于记录和读取Jupyter和nteract笔记本数据的库

项目描述

scrapbook logo

scrapbook

Travis Build Status image Documentation Status badge badge Code style: black

scrapbook库将笔记本的数据值和生成的可视化内容记录为“碎片”。记录的碎片可以在未来阅读。

有关如何使用scrapbook的更多信息,请参阅scrapbook文档

警告:这是旧的包名nteract-scrapbook -- 请今后安装scrapbook,因为不会对此旧包名发布新版本。

用例

笔记本用户可能希望在笔记本执行期间记录产生的数据。这些记录的数据(碎片)可以在以后使用或在工作流程中作为输入传递给另一个笔记本。

具体来说,scrapbook让您

  • 持久化笔记本中的数据和可视化内容显示为碎片
  • 回忆任何持久化的数据碎片
  • 总结笔记本集合

支持的Python版本

该库的长期支持目标是Python 3.5及以上。目前它也支持Python 2.7,直到Python 2在2020年停止服务。在此日期之后,Python 2的支持将停止,只维护3.x版本。

安装

使用pip安装

pip install nteract-scrapbook

对于安装可选的IO依赖项,您可以指定单个存储捆绑包,如s3azure

pip install nteract-scrapbook[s3]

或使用all

pip install nteract-scrapbook[all]

模型和术语

Scrapbook定义以下项目

  • scraps:可序列化的数据值和可视化,如字符串、对象列表、pandas数据框、图表、图像或数据引用。
  • notebook:一个包含额外与scraps交互方法的封装nbformat笔记本对象。
  • scrapbook:一组笔记本,具有询问集合的接口。
  • encoders:数据到/从笔记本存储格式的注册翻译器。

scrap模型

scrap模型在元组中包含一些关键属性,包括

  • name:scraps的名称
  • data:由scrapsbook api调用捕获的任何数据
  • encoder:用于将数据编码/解码到/从笔记本的编码器的名称
  • display:由IPython用于显示视觉内容的任何显示数据

API

Scrapbook添加了一些基本的API命令,这些命令可以用于保存和检索数据,包括

  • glue用于持久化带有或没有显示输出的scraps
  • read_notebook读取一个笔记本
  • scraps提供所有scraps的可搜索字典,按名称排序
  • reglue从另一个笔记本复制一个scraps到当前笔记本
  • read_notebooks从一个给定的路径读取许多笔记本
  • scraps_report显示收集的scraps的报告
  • papermill_dataframepapermill_metrics用于向后兼容两个已弃用的papermill功能

以下各节提供了关于这些API命令的更多详细信息。

glue用于持久化scraps

在给定的笔记本单元中记录一个scrap(数据或显示值)。

在稍后检查输出笔记本时可以检索该scrap(记录的值)。

"""glue example for recording data values"""
import scrapbook as sb

sb.glue("hello", "world")
sb.glue("number", 123)
sb.glue("some_list", [1, 3, 5])
sb.glue("some_dict", {"a": 1, "b": 2})
sb.glue("non_json", df, 'arrow')

以后可以使用scrapbook库从输出笔记本中恢复scraps

# read a notebook and get previously recorded scraps
nb = sb.read_notebook('notebook.ipynb')
nb.scraps

scrapbook将根据任何注册数据编码器的值类型来暗示存储格式。或者,可以通过将encoder参数设置为特定编码器的注册名称(例如"json")来覆盖暗示的编码格式。

这些数据通过生成一个特殊媒体类型来持久化,该类型标识内容编码格式和数据。这些输出在笔记本渲染中不一定可见,但仍然存在于文档中。然后Scrapbook可以通过读取这些单元输出在未来重新激活与笔记本关联的数据。

带有显示输出

要显示具有可见显示输出的命名scraps,您需要指示该scraps是直接可渲染的。

这可以通过切换display参数来完成。

# record a UI message along with the input string
sb.glue("hello", "Hello World", display=True)

该调用将保存Scrap对象的数据和显示属性,使其可见,同时将原始数据编码。这依赖于IPython.core.formatters.format_display_data函数将数据对象转换为显示和元数据字典,以便笔记本内核解析。

另一种可以使用的方法是指定仅保存显示数据,而不保存原始对象。这可以通过将编码器设置为display来实现。

# record an image without the original input object
sb.glue("sharable_png",
  IPython.display.Image(filename="sharable.png"),
  encoder='display'
)

最后,可以通过将列表、元组或字典对象作为显示参数传递来控制生成的媒体类型。

sb.glue("media_as_text_only",
  media_obj,
  encoder='display',
  display=('text/plain',) # This passes [text/plain] to format_display_data's include argument
)

sb.glue("media_without_text",
  media_obj,
  encoder='display',
  display={'exclude': 'text/plain'} # forward to format_display_data's kwargs
)

与数据碎片一样,这些可以在稍后通过访问碎片的 display 属性来检索。尽管通常人们会使用笔记本的 reglue 方法(如下文所述)。

read_notebook读取一个笔记本

从指定在 path 的位置加载的笔记本对象读取。您已经在上述API调用示例中看到了该函数的使用方法,但基本上这提供了一个对 nbformat 的 NotebookNode 的薄包装,并具有提取碎片的功能。

nb = sb.read_notebook('notebook.ipynb')

此笔记本对象遵循 nbformat的json模式,允许访问其所需字段。

nb.cells # The cells from the notebook
nb.metadata
nb.nbformat
nb.nbformat_minor

还提供了一些其他方法,其中大部分在下文中有更详细的说明。

nb.scraps
nb.reglue

该抽象还使保存的内容以数据框的形式可用,引用每个键和来源。在以后的版本中还将提供更多这些方法。

# Produces a data frame with ["name", "data", "encoder", "display", "filename"] as columns
nb.scrap_dataframe # Warning: This might be a large object if data or display is large

笔记本对象还具有一些与papermill的笔记本对象模型向后兼容的旧函数。因此,它可以用来读取papermill执行统计以及碎片抽象。

nb.cell_timing # List of cell execution timings in cell order
nb.execution_counts # List of cell execution counts in cell order
nb.papermill_metrics # Dataframe of cell execution counts and times
nb.papermill_record_dataframe # Dataframe of notebook records (scraps with only data)
nb.parameter_dataframe # Dataframe of notebook parameters
nb.papermill_dataframe # Dataframe of notebook parameters and cell scraps

笔记本读取器依赖于 papermill的注册iorw 以启用对各种来源的访问,例如但不限于S3、Azure和Google Cloud。

scraps 提供一个名称 -> 碎片查找

scraps 方法允许访问特定笔记本中的所有碎片。

nb = sb.read_notebook('notebook.ipynb')
nb.scraps # Prints a dict of all scraps by name

此对象还有一些额外的方便转换和执行的方法。

nb.scraps.data_scraps # Filters to only scraps with `data` associated
nb.scraps.data_dict # Maps `data_scraps` to a `name` -> `data` dict
nb.scraps.display_scraps # Filters to only scraps with `display` associated
nb.scraps.display_dict # Maps `display_scraps` to a `name` -> `display` dict
nb.scraps.dataframe # Generates a dataframe with ["name", "data", "encoder", "display"] as columns

这些方法允许简单用例而不需要深入模型抽象。

reglue 将碎片复制到当前笔记本中

使用 reglue,可以将任何粘合到笔记本中的碎片粘合到当前笔记本中。

nb = sb.read_notebook('notebook.ipynb')
nb.reglue("table_scrap") # This copies both data and displays

任何数据或显示信息将被原封不动地复制到当前正在执行的笔记本中,就像用户再次在原始源上调用 glue 一样。

在过程中也可以重命名碎片。

nb.reglue("table_scrap", "old_table_scrap")

最后,如果希望在不需要检查存在的情况下尝试重新粘合,则可以将 raise_on_missing 设置为在失败时仅显示消息。

nb.reglue("maybe_missing", raise_on_missing=False)
# => "No scrap found with name 'maybe_missing' in this notebook"

read_notebooks 读取多个笔记本

将给定 path 中所有笔记本读取到碎片簿对象中。

# create a scrapbook named `book`
book = sb.read_notebooks('path/to/notebook/collection/')
# get the underlying notebooks as a list
book.notebooks # Or `book.values`

该路径重用 papermill的注册iorw 以列出和读取来自各种来源的文件,从而使非本地url能够加载数据。

# create a scrapbook named `book`
book = sb.read_notebooks('s3://bucket/key/prefix/to/notebook/collection/')

可以使用碎片簿(在此示例中为 book)来回忆笔记本集合中的所有碎片。

book.notebook_scraps # Dict of shape `notebook` -> (`name` -> `scrap`)
book.scraps # merged dict of shape `name` -> `scrap`

scraps_report显示收集的scraps的报告

可以使用碎片簿集合生成集合中所有碎片的 scraps_report,作为Markdown结构化输出。

book.scraps_report()

此显示可以根据碎片和笔记本名称进行筛选,以及启用或禁用显示的整体标题。

book.scraps_report(
  scrap_names=["scrap1", "scrap2"],
  notebook_names=["result1"], # matches `/notebook/collections/result1.ipynb` pathed notebooks
  header=False
)

默认情况下,报告将仅填充视觉元素。要报告数据元素,请设置 include_data。

book.scraps_report(include_data=True)

papermill支持

最后,碎片簿为废弃的papermill功能提供了两个向后兼容的功能。

book.papermill_dataframe
book.papermill_metrics

编码器

编码器可以通过键名访问注册在 encoders.registry 对象上的编码器对象。要注册新的数据编码器,只需调用

from encoder import registry as encoder_registry
# add encoder to the registry
encoder_registry.register("custom_encoder_name", MyCustomEncoder())

encode类必须实现两个方法,encodedecode

class MyCustomEncoder(object):
    def encode(self, scrap):
        # scrap.data is any type, usually specific to the encoder name
        pass  # Return a `Scrap` with `data` type one of [None, list, dict, *six.integer_types, *six.string_types]

    def decode(self, scrap):
        # scrap.data is one of [None, list, dict, *six.integer_types, *six.string_types]
        pass  # Return a `Scrap` with `data` type as any type, usually specific to the encoder name

这可以读取将碎片转换为表示其内容或位置的json对象,并将这些字符串重新加载到原始数据对象中。

文本

一种基本的字符串存储格式,将数据保存为python字符串。

sb.glue("hello", "world", "text")

json

sb.glue("foo_json", {"foo": "bar", "baz": 1}, "json")

pandas

sb.glue("pandas_df",pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}), "pandas")

papermill废弃的 record 功能

scrapbook 提供了一个强大且灵活的记录模式。这个库取代了 papermill 现有的 record 功能。

papermill record 的文档存在于 ReadTheDocs 上。简要来说,废弃的 record 函数

pm.record(name, value):允许将值与笔记本一起保存 [API 文档]

pm.record("hello", "world")
pm.record("number", 123)
pm.record("some_list", [1, 3, 5])
pm.record("some_dict", {"a": 1, "b": 2})

pm.read_notebook(notebook):之后可以使用 pandas 读取输出笔记本到 dataframe 中以恢复记录的值。例如

nb = pm.read_notebook('notebook.ipynb')
nb.dataframe

Papermill record 废弃的理由

Papermill 的 record 函数因为以下限制和挑战而被废弃

  • record 函数不遵循 papermill 线性执行笔记本的模式。将 record 描述为 papermill 的附加功能显得很尴尬,实际上感觉像是在描述一个发展较慢的库。
  • 记录/读取需要将所有数据转换为 JSON,这对于 dataframe 来说是繁琐且痛苦的过程。
  • 将记录的值读入 dataframe 会产生不直观的数据 frame 形状。
  • 与其他允许注册自定义操作符的 papermill 组件相比,模块化和灵活性较低。

为了克服 Papermill 中的这些限制,决定创建 Scrapbook

项目详情


下载文件

下载适合您平台的应用程序。如果您不确定该选择哪一个,请了解更多关于 安装包 的信息。

源分布

nteract-scrapbook-0.4.2.tar.gz (133.3 kB 查看哈希值)

上传时间

构建分布

nteract_scrapbook-0.4.2-py3-none-any.whl (35.0 kB 查看哈希值)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面