astropy / astropy/astropy

BUG: indexing a `QTable` with a `Quantity` column doesn't work as expected

Open
#16,036 8 comments 0 reactions 0 assignees View on GitHub
Bug table
Dominant language
Python
Stars
5.3k
Forks
2.2k
Avg merge
1d 19h
Merged PRs (30d)
75

Description

```python
import astropy.units as u
from astropy.table import QTable

t = QTable({"a": u.Quantity([0], unit="m")})
t.add_index(["a"])
t.loc[t["a"][0]]
```
fails with
```python-traceback
Traceback (most recent call last):
File "/Users/clm/dev/astropy-project/coordinated/astropy/t.py", line 6, in
t.loc[t["a"][0]]
~~~~~^^^^^^^^^^^
File "/Users/clm/dev/astropy-project/coordinated/astropy/astropy/table/index.py", line 888, in __getitem__
rows = self._get_rows(item)
^^^^^^^^^^^^^^^^^^^^
File "/Users/clm/dev/astropy-project/coordinated/astropy/astropy/table/index.py", line 867, in _get_rows
for key in item:
File "/Users/clm/dev/astropy-project/coordinated/astropy/astropy/units/quantity.py", line 1283, in __iter__
raise TypeError(
TypeError: 'Quantity' object with a scalar value is not iterable
```

In contrast, the following works
```python
import astropy.units as u
from astropy.table import QTable

t = QTable({"a": u.Quantity([0], unit="m")})
t.add_index(["a"])
t.loc[t["a"][0].value] # passing `.value` instead of the full quantity
```

Using a `Table` instead of a `QTable` also works as expected
```python
import astropy.units as u
from astropy.table import Table

t = Table({"a": u.Quantity([0], unit="m")})
t.add_index(["a"])
t.loc[t["a"][0]]
```

I'm not 100% sure the current behaviour is actually buggy: this is a matter of intent.
This was first discussed in #15826 where @taldcroft found that multi-indexing wouldn't work seamlessly for `Quantity` indices, as he assumed.

This report is adapted from my comment https://github.com/astropy/astropy/issues/15826#issuecomment-1942541936_

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the QTable example and read astropy/table/index.py around _get_rows (line 867) and __getitem__ (line 888). Review the discussion in issue #15826 to determine the intended behavior for Quantity-valued indexes, then add or update tests so the chosen behavior is explicit and the example is handled consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.