Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting single iPython Jupyter Notebook cell output

I am playing around with formatting my iPython Notebooks in order to make them more into a logbook.

The use of display(HTML()) constructs makes everything nice and relatively easy to organize.

I would like to use the output of certain cells in other media, like for instance presentations. The way I do it now is by taking a screenshot of the area, but then everything becomes pixels and there is no refinement possible.

Is there a way to render the output of a single cell in some useful format?

like image 524
Michele Ancis Avatar asked Jun 02 '16 13:06

Michele Ancis


People also ask

What is %% capture in Jupyter notebook?

Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.

How do I save a Jupyter notebook output as a CSV?

If you have data in pandas DataFrame then you can use . to_csv() function from pandas to export your data in CSV .


1 Answers

There is no possible way to export a single cell output in Jupyter, as of now, but what you can do is to convert the entire notebook to a more useful format and then trim out only the parts that you need. This is not optimal, but it's still better than your current workaround, at least concerning the quality of the output.

You can do this in different ways:

  1. File -> Export Notebook as... -> Your preferred file format
  2. If you want to do it programmatically, you can use nbconvert from the command line like this:

    nbconvert --to (your preferred output format) yourNotebook.ipynb

You can also do it from inside your notebook, executing this code in a cell (for HTML, in this example):

from nbconvert import HTMLExporter
import codecs
import nbformat

notebook_name = 'YOUR_NOTEBOOK_NAME.ipynb'
output_file_name = 'output.html'

exporter = HTMLExporter()
output_notebook = nbformat.read(notebook_name, as_version=4)

output, resources = exporter.from_notebook_node(output_notebook)
codecs.open(output_file_name, 'w', encoding='utf-8').write(output)

Most libraries, though, allow you to export the result of your program to any desired outpout (pandas, matplotlib, altair...), so you probably should try to use them.

like image 77
TrinTragula Avatar answered Sep 22 '22 08:09

TrinTragula