Home > Software engineering >  is it possible to add cells or delete cells using codes in jupyter notebook?
is it possible to add cells or delete cells using codes in jupyter notebook?

Time:02-26

is it possible to use code to add or delete cells in jupyter notebook?

For example: can we use a for loop in range of 10 that creates 10 cells and perhaps executes something in it ?

CodePudding user response:

Most of the code is provided in a discussion in this GitHub issue.

You could use the following code to programmatically append 10 new code cells below the current cell.

from IPython.display import display, Javascript

# create 10 cells
for i in range(10):
    display(Javascript('''
        let cell = IPython.notebook.insert_cell_{}("{}")
        cell.set_text("{}")
        '''.format('below', 'code', "print('Hello World!')")));
    add_cell('print(\'Hello World\')')

If you want to execute one, or possibly all of them, you could use the following code.

# execute the 3rd cell of the notebook
display(Javascript('IPython.notebook.execute_cell(3)'))

The above will execute the third cell in the notebook. You could loop over the indices that you want to execute.

  • Related