I think this won’t work, as you are not changing the length of the dataset and this might use an invalid index.
Would it be possible to iterate the dataset once, store all invalid indices, and remove them before creating your new “clean” dataset?