Reputation: 1720
Is there a way to selectively hide one specific input or output cell in IPython notebook?
I could only find the below code to show / hide all input cells.
http://blog.nextgenetics.net/?e=102
But what if I only want to hide the first input cell of a notebook?
Upvotes: 66
Views: 143749
Reputation: 28926
This is now built into nbconvert (as of 5.3.0) using tags.
Here's an example removing a specific cell from the output, using this notebook, which is also included at the end of this post. The example has three cells: a markdown cell, a code cell that will be hidden, and a code cell that will not be hidden.
remove_cell
tag to any cells you want to hide using the tag editor built into the notebook or JupyterLab (the specific name "remove_cell" doesn't matter)jupyter nbconvert nbconvert-example.ipynb --TagRemovePreprocessor.remove_cell_tags='{"remove_cell"}'
Any cells with the tag remove_cell
will be removed from the output.
In addition to entire cells, you can filter just inputs or just outputs:
TagRemovePreprocessor.remove_input_tags
TagRemovePreprocessor.remove_single_output_tags
TagRemovePreprocessor.remove_all_outputs_tags
Here's the full source for the notebook used in this example:
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's an example of how to hide cells with nbconvert."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"tags": [
"remove_cell"
]
},
"outputs": [],
"source": [
"# This cell is hidden\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>A</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>2</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" A\n",
"0 1\n",
"1 2"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame({\"A\": [1, 2]})"
]
}
],
"metadata": {
"celltoolbar": "Tags",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
Upvotes: 74
Reputation: 1
I stumbled over a similar problem and got it solved with a simple javascript block:
To just hide the first cell in the notebook:
%%js
Jupyter.notebook.get_cell(0).element.hide()
To hide all cells with a certain tag (e.g., hide_tag
):
%%js
cells = Jupyter.notebook.get_cells();
for (i = 0; i < cells.length; i++) {
cur_cell = cells[i];
tags = cur_cell._metadata.tags;
if (tags != undefined) {
for (j = 0; j < tags.length; j++) {
if (tags[j]=="hide_tag") {cur_cell.element.hide();}
}}}
Note that element
also has the inverse function element.show()
which again reveals the respective cells.
Upvotes: 0
Reputation: 1
The answer TomAugspurger give worked for me. Jupyter lab has a "property inspector" (gear icon in the top right). In the "cell tag" section is an easy way to add tags. "to_remove" was already set and just a click away from success.
I was creating a PDF document and did not want any input or "to_remove" outputs. My final command line was
jupyter nbconvert "nbconvert_example.ipynb" --to pdf --no-input --TagRemovePreprocessor.remove_cell_tags='to_remove'
Upvotes: 0
Reputation: 1601
I couldn't get any of the above solutions to work, when I wanted to hide inputs in notebooks exported to HTML. I didn't even need a toggle to show the hidden elements.
Thus, my solution was to simply export the notebook as HTML and use the Chrome's Inspect tool to remove inputs.
You can delete the cell's input/output (or whole cells) there. After editing, press ctrl + s to save edited file.
To be more specific the inputs and outputs of code cells have the following divs, you can delete:
<div class="jp-Cell-inputWrapper">...</div>
<div class="jp-Cell-outputWrapper">...</div>
They are inside the code cell:
<div class="jp-Cell jp-CodeCell jp-Notebook-cell ">...</div>'
The code cell is inside the <body>
tags so it won't bee too hard to find in inspector. Easiest way to find it is to right click an empty spot in the cell and select Inspector. Then you can find the tags mentioned above in the Inspector window. Editing the HTML in a text editor is hard, because the files can be about 20 000 lines long.
Upvotes: 1
Reputation: 163
Using that code:
# @hidden
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('.cm-comment:contains(@hidden)').closest('div.input').hide();
} else {
$('.cm-comment:contains(@hidden)').closest('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
The raw code for this IPython notebook is by default hidden for easier reading.
To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.''')
Extracted from here and modified by me.
You can hide lines with comment:
# @hidden
Upvotes: 3
Reputation: 22449
Regarding the output, in Jupiter notebook, there is also an option on the bar:
You can Clear
the output or you can hide it using Toggle
. In both cases, you won't delete any variable calculated inside the cell.
Upvotes: 7
Reputation: 484
In case anyone finds excluding all code cells helpful (which is not what is asked here), you can add this flag nbconvert --TemplateExporter.exclude_code_cell=True
Upvotes: 6
Reputation: 99
Ok, after trying without success the answers here stated. I found this extension of kirbs.Hide_code nbextension It works just fine. But it is recommended to do the following:
First of all, make sure that you have updated your jupyter, the nbconverter, the nbconverter extensiones and the jupyter serverextension. If you did that then you can do the following in the anaconda prompt (Opened with admin priviledges):
pip install hide_code
jupyter nbextension install --py hide_code
jupyter nbextension enable --py hide_code
jupyter serverextension enable --py hide_code
Finally if you are using anaconda distribution to open your notebooks then make sure of also using these commands:
jupyter nbextension install --sys-prefix --py hide_code
jupyter nbextension enable --sys-prefix --py hide_code
jupyter serverextension enable --sys-prefix --py hide_code
If there are no error on the execution of these commands then you will be able to see and use the hide code options in the toolbar as it is shown here:
Done! If you use the button for exporting and voilá!
Good luck
Upvotes: 9
Reputation: 2538
This is an extension of Mathmagician's answer, which enables you to:
What you need to do is run the following code first to define the hide_toggle
function:
from IPython.display import HTML
import random
def hide_toggle(for_next=False):
this_cell = """$('div.cell.code_cell.rendered.selected')"""
next_cell = this_cell + '.next()'
toggle_text = 'Toggle show/hide' # text shown on toggle link
target_cell = this_cell # target cell to control with toggle
js_hide_current = '' # bit of JS to permanently hide code in current cell (only when toggling next cell)
if for_next:
target_cell = next_cell
toggle_text += ' next cell'
js_hide_current = this_cell + '.find("div.input").hide();'
js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))
html = """
<script>
function {f_name}() {{
{cell_selector}.find('div.input').toggle();
}}
{js_hide_current}
</script>
<a href="javascript:{f_name}()">{toggle_text}</a>
""".format(
f_name=js_f_name,
cell_selector=target_cell,
js_hide_current=js_hide_current,
toggle_text=toggle_text
)
return HTML(html)
And then use it in cells like this:
x = 1
y = 2
print('Result is {} + {}'.format(x, y))
hide_toggle()
Or this (if you want to toggle the next cell)
hide_toggle(for_next=True)
Upvotes: 49
Reputation: 1705
The @Mathmagician solution is almost perfect, but has many side effects.
More correct would be like:
from IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Toggle Code"></form>
'''
toggle_code_prepare_str = '''
<script>
function code_toggle() {
if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
$('div.cell.code_cell.rendered.selected div.input').hide();
} else {
$('div.cell.code_cell.rendered.selected div.input').show();
}
}
</script>
'''
display(HTML(toggle_code_prepare_str + toggle_code_str))
def toggle_code():
display(HTML(toggle_code_str))
The call toggle_code
than may be placed in some code cell before other code, so if code in the cell is executed slowly, won't be side effects. Also it solves the problem with Run Cells and Select/Insert Below
It adds the toggle button, but the initial state can't be managed
Upvotes: 2
Reputation: 197
Your solution for hiding all input cells can be altered to affect just a single cell.
Change 'div.input'
to 'div.cell.code_cell.rendered.selected div.input'
.
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.cell.code_cell.rendered.selected div.input').hide();
} else {
$('div.cell.code_cell.rendered.selected div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
To show/hide this cell's raw code input, click <a href="javascript:code_toggle()">here</a>.''')
This works because when you click the "click here" prompt on a cell's output, that cell becomes the "selected" cell and thus becomes hidden.
If your JavaScript code executes a toggle within the <script></script>
tags with a line of code like this
$( document ).ready(code_toggle);
then the block will automatically ("by default") be hidden when the input cell is executed.
Keep in mind that if you do make cell inputs hidden by default, you must run the cell with the Run Cells (Ctrl+Return) option, not the Run Cells and Select/Insert Below options.
These will prompt the move of the "selected" label to the next cell before executing the JavaScript, so you may end up hiding a cell that doesn't have the "click here" toggle link in its output. In which case you will have to inspect the cell and navigate through the relevant tags and change display='none';
to display='block';
.
Note that this must be put at the end of any code in your cell, and that you need to have imported HTML from IPython.display before executing this code. You can do so by executing
from IPython.display import HTML
Upvotes: 12
Reputation: 8335
Here's a method that allows you to hide cells from the HTML/PDF output by editing the cell metadata only.
Versions I'm using:
$ jupyter notebook --version
4.1.0
$ jupyter nbconvert --version
4.2.0
jupyter notebook
localhost:8888/nbextensions
(or whatever port you started on) and activate Printview
localhost:8888/tree
, create a new notebook and go into itprint("You can see me") #but not me
View
> Cell Toolbar
> Edit Metadata
Edit Metadata
button now showing to the top right of the cell'hide_input':True
to the json e.g. mine looked like {
"collapsed": false,
"hide_input": true,
"trusted": true
}
afterjupyter nbconvert --to pdf --template printviewlatex.tplx notebookname.ipynb
(if your notebook is called notebookname.ipynb.ipynb
)You should now have a document called notebookname.pdf in the directory. Hopefully it should have just the text You can see me
in it...fingers crossed.
Upvotes: 15
Reputation: 1720
Finally found it's possible using this extension.
https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/usability/hide_input.js
Upvotes: 3