118

I use Jupyter notebook. I accidentally deleted a cell, and I can't go step back.

How can I recover the notebook cell?

sc_
  • 197
  • 1
  • 15
HISI
  • 3,641
  • 2
  • 24
  • 43

6 Answers6

179

If you go to "Edit", there's an option for "Undo Delete Cells".

If you are familiar with shortcuts, you can do cmd + shift + p and then type in undo to recover as well. No need to moving your mouse around.

Tshilidzi Mudau
  • 5,472
  • 6
  • 32
  • 44
TYZ
  • 6,636
  • 4
  • 19
  • 44
94

First, switch to command mode by pressing ESC, then you can press Z to recover the deleted cells. It works even in Jupyter Lab which doesn't have "Undo Delete Cells" option under "Edit" tab.

nik7
  • 747
  • 2
  • 8
  • 17
Rishabh Agrahari
  • 2,694
  • 1
  • 18
  • 20
37

If the notebook kernel is still running and you executed the cell, you can find the content of all cells, including the deleted ones in _ih. For example, the last five cells:

_ih[-5:]
Mike Müller
  • 71,943
  • 15
  • 139
  • 140
  • 1
    In the sad case of closing the kernel, I've found out that simply opening an ipython console and scrolling back in history using the up arrow, shows the executed deleted cell. That's the only thing that worked for me. – Itamar Katz Feb 27 '19 at 11:04
  • 1
    A workaround to recover changes: export your IPython history in a plain-text file by calling "%history -g" You can also do it for a specific filename: %history -g -f filename What does -g do? – Without -g it exports the history for the current session. With -g it exports history for all sessions. – Serendipity Jun 24 '19 at 14:41
  • Works for me. Thanks :-) – Maksym Kozlenko Mar 25 '21 at 10:48
24

If you need to undo something deleted inside a cell, press:
CTRL/CMD + Z

If you need to recover an entire deleted cell hit:
ESC + Z.
Especially this second tip might be useful if you delete a lot of cells by mistake.

Sander van den Oord
  • 6,558
  • 1
  • 23
  • 51
7

if you've already restarted your kernel then %history or _ih[:n] would be empty. You can hope for a recent checkpoint to revert to. You can do this with File > Revert to Checkpoint.

If you want to be sure what's in the checkpoint before you revert - in your working directory (the one your notebook lives in) you'll have a hidden folder that stores your checkpoints. cd .ipynb_checkpoints will get you there. You can look inside the file and see if your lost code is there.

This has just saved me. Found this in an answer here

0

First, do "ESC" hot key, then you can press Z to recover the deleted cells.

Jupyter Lab work well.

J.Lucas
  • 1
  • 1