63

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?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Pan Yan
  • 1,622
  • 1
  • 18
  • 21
  • it seems there is no easy way? I think it would be useful as sometimes you do want to hide some of the cells that is too long or not especially relevant to the context. – Pan Yan Jul 24 '15 at 00:02
  • 4
    Answering for folks in 2018. You could switch to Jupyter Lab. There's a hover-over tool that shows up on the left hand side of the cell (Both code and output), clicking which *folds* that cell – Lelouch Lamperouge Feb 20 '18 at 22:31
  • This snippet adds a button to hide cells having a tag named 'hideable' (needs nbconvert 5.6.1): https://gitlab.tetras-libre.fr/tetras-libre/jupyter/nbviewer/snippets/6 – daxid Mar 17 '20 at 14:24
  • Hello. I was looking for this query since a long time. None of the answers here work for hiding the cell in a notebook, especially when we load the .ipynb file. Have you found out how to do that? Or was your query different than mine? – Meet Oct 04 '21 at 11:19
  • 2
    For me, there are more than hundreds of cells. Out of those, there are some where the code is to be shown, while others where code is not to be shown. I need the "not to be shown" cells to be hidden the moment the ipynb file is opened. Or after running one cell after it is opened. Again, I do not want the viewers to see that I ran a cell to hide others, so again the answers on this page do not work. Any way to do this? – Meet Oct 04 '21 at 11:21

13 Answers13

72

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.

  1. 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)
  2. 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.

hidden

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
András Aszódi
  • 8,948
  • 5
  • 48
  • 51
TomAugspurger
  • 28,234
  • 8
  • 86
  • 69
  • 5
    Thanks for this. Does it however only work for html output? Nothing seems to be hidden in the resulting .ipynb file if using `jupyter nbconvert --to notebook --inplace ...`. – qAp Jan 29 '18 at 02:56
  • 6
    I had to swap the quotes on Windows; e.g.: `jupyter nbconvert nbconvert-example.ipynb --TagRemovePreprocessor.remove_cell_tags="{'a', 'b'}"`. – Ninjakannon Sep 09 '18 at 18:47
  • 2
    I had to change the curly braces to square brackets (`list`) to get this to work, i.e. `--TagRemovePreprocessor.remove_cell_tags='["remove_cell"]'` – craymichael Jul 08 '19 at 20:05
  • 1
    Note that in jupyter lab, in order to add a tag you need to add the following to cell metadata: `tags: ["remove_cell"]` – ostrokach Jan 23 '20 at 17:11
  • Any way to hide the cells when an ipynb file is opened? I need to hide them in the notebook itself, and do not intend to convert the notebook into a separate pdf or html file. – Meet Oct 04 '21 at 12:24
  • 1
    this doesn't seem to work when exporting to pdf – AlvaroP Mar 03 '22 at 14:48
  • Just to note, with the latest version of traitlets the nbconvert command should be `jupyter nbconvert nbconvert-example.ipynb --TagRemovePreprocessor.remove_cell_tags remove_cell` – Matt Pitkin Oct 18 '22 at 15:35
48

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

demo of the toggle

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)
mit
  • 11,083
  • 11
  • 50
  • 74
Ferrard
  • 2,260
  • 3
  • 22
  • 26
  • Minimal python version seems to be 3.6 for the above code. Will work below 3.6 for anyone who converts the two f-strings `f' ....'` to old style – mit Oct 05 '18 at 17:05
  • 2
    Ah right, thanks, I changed it now to the backward compatible way of string formatting – Ferrard Oct 11 '18 at 12:24
  • @Ferrard, thank you for RISE presentation reference - had no idea about such option. – garej Mar 09 '19 at 06:08
  • 1
    This is great! Thanks – Sandalaphon May 30 '19 at 13:40
  • This is what I'm looking for, thanks. Can this also be made as a button though? – NonSleeper Jun 25 '20 at 12:41
  • 3
    Note this only works for Jupyter Notebook. And this does not work with Jupyter Lab or exported as html. – Nor.Z Feb 01 '21 at 19:05
  • In case somebody needs to hide the previous cell, simply replace .next() with .prev() in the code above – charmd Jan 07 '22 at 13:22
  • in the instance where someone wants to have the default as toggle on, how could the code be modified? So when notebook is executed, the cells are hidden rather than user selecting the toggle to hide. – paranormaldist Feb 22 '22 at 12:40
15

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

  1. Download the ipython notebook extension templates by following install instructions on Github: pip install https://github.com/ipython-contrib/IPython-notebook-extensions/tarball/master
  2. run jupyter notebook
  3. go to localhost:8888/nbextensions (or whatever port you started on) and activate Printview
  4. go back to localhost:8888/tree, create a new notebook and go into it
  5. create a code cell with some code in it that produces output e.g. print("You can see me") #but not me
  6. go to View > Cell Toolbar > Edit Metadata
  7. click the Edit Metadata button now showing to the top right of the cell
  8. add 'hide_input':True to the json e.g. mine looked like { "collapsed": false, "hide_input": true, "trusted": true } after
  9. save notebook
  10. go back to the terminal and execute jupyter 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.

James Owers
  • 7,948
  • 10
  • 55
  • 71
12

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
Mathmagician
  • 177
  • 1
  • 6
  • 3
    I'm using this solution. I have it hidden, but then when I export as html the code is displayed. How can I export the notebook without displaying that specific cell? – nahusznaj Jun 01 '18 at 15:24
  • Tried a lot of things. This was the only thing that *actually* works. Thanks!! – Uncle Meh Mar 13 '22 at 22:30
9

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):

  1. pip install hide_code
  2. jupyter nbextension install --py hide_code
  3. jupyter nbextension enable --py hide_code
  4. 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:

  1. jupyter nbextension install --sys-prefix --py hide_code
  2. jupyter nbextension enable --sys-prefix --py hide_code
  3. 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:

Hide_code toolbar

Done! If you use the button for exporting and voilá!

Export Button

Good luck

F4laF
  • 99
  • 1
  • 1
7

Regarding the output, in Jupiter notebook, there is also an option on the bar: enter image description here 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.

G M
  • 20,759
  • 10
  • 81
  • 84
  • Clearing the output is not the same as omitting or hiding the output. It's just clearing the output cell until the input cell is run again. That's not a solution. – Benjamin R Aug 31 '23 at 13:32
6

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

shouldsee
  • 434
  • 7
  • 7
3

Finally found it's possible using this extension.

https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/usability/hide_input.js

Pan Yan
  • 1,622
  • 1
  • 18
  • 21
  • Update: This seems to have been merged to https://github.com/ipython-contrib/IPython-notebook-extensions/ – Hans Apr 28 '16 at 12:20
3

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
2

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

Роман Коптев
  • 1,555
  • 1
  • 13
  • 35
  • 2
    How can I make the default view when I run this code to actually toggle the code off? – newbie Jan 20 '20 at 08:15
  • This works to some extent. But if we do this and accidentally or deliberately refresh (reload) the notebook window (or browser window), then the toggle buttons will next time refresh the browser window instead of toggling unless we ran each and every toggle function call again. I do not know what is causing that though. – Meet Oct 04 '21 at 12:46
1

Remove inputs and outputs in notebooks exported to HTML

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.

Mikko Haavisto
  • 991
  • 7
  • 10
0

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'

0

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.