API: consider undeprecating Series.item() ? · Issue #29250 · pandas-dev/pandas (original) (raw)
I recently ran into this as well (but forgot to open an issue), and raised now by @alexiswl in #18262 (comment)
Series.item()
was a consequence of (historically) inheriting from np.ndarray, and was deprecated (like a set of other ndarray-inhertited methods/attributes) a while ago.
While .item()
could also be used to select the "i-th" element (.item(i)
), and this use case is certainly redundant (not arguing here to get that aspect back), there is one use case where item()
can actually be useful: if you do not pass i, the method returns the element of the Series only if it has one element, otherwise it errors.
Such a situation can typically occur if you use boolean indexing (or query
) to select a single element. Eg in cases like s[s == 'val']
or df.loc[df['col1'] == 'val', 'col2']
where you know the condition should yield a single element.
You then typically want the scalar element as result, but those two code snippets give you a Series of one element. In those cases, you could use item()
to retrieve it: s[s == 'val'].item()
.
I saw some people using .item()
exactly for this use case, so wondering if it is worth to keep it for this (only the version without passing i).
The logical alternative is doing a .iloc[0]
, but .item()
has the advantage of guaranteeing there was actually only one result item.