# Advanced/Fancy indexing across batches

**URL:** <https://discuss.pytorch.org/t/advanced-fancy-indexing-across-batches/103445>\
**Category:** vision\
**Created:** [November 19, 2020, 10:46pm UTC](https://discuss.pytorch.org/t/advanced-fancy-indexing-across-batches/103445 "2020-11-19T22:46:08Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Pietro\_Cicalese](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pietro_cicalese/32/27365_2.png) [@Pietro\_Cicalese](https://discuss.pytorch.org/u/Pietro_Cicalese)\
**Post date:** [November 20, 2020, 7:45pm UTC](https://discuss.pytorch.org/t/advanced-fancy-indexing-across-batches/103445/2 "2020-11-20T19:45:59Z")

</div>

You can do this using:

```auto
def batched_index_select(input, dim, index):
    for ii in range(1, len(input.shape)):
        if ii != dim:
            index = index.unsqueeze(ii)
    expanse = list(input.shape)
    expanse[0] = -1
    expanse[dim] = -1
    index = index.expand(expanse)
    return torch.gather(input, dim, index)

```

Taken from [here.](https://discuss.pytorch.org/t/batched-index-select/9115)

---

_[View the full topic](https://discuss.pytorch.org/t/advanced-fancy-indexing-across-batches/103445)._
