How to hide one specific cell (input or output) in IPython Notebook?
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?
Solution 1:
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. The example has three cells: a markdown cell, a code cell that will be hidden, and a code cell that will not be hidden.
- Add the
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) -
Convert with nbconvert
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
Solution 2:
This is an extension of Mathmagician's answer, which enables you to:
- toggle just a single cell (the JS function name has a random suffix, so if used more than one time, it would not conflict with other usages)
- toggle the cell below the current cell - this is super handy in RISE presentations where you may want to show the code, but then hide it to display its output
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)