LondonRob
LondonRob

Reputation: 78803

Select one item from Series and keep the index

If I select a single item from a pd.Series using either .loc or just straightforward indexing, a single value is returned.

Pandas automatically 'squeezes' the result:

>>> s = pd.Series(['A', 'B', 'C'], index=[10, 20, 30])
>>> s[10]
'A'
>>> s.loc[10]
'A'

Although this is almost always what we want, sometimes I'd like to know "where" a single value came from in a bigger series.

How can I prevent this default squeezing? In other words, I'd like to create a 1-element series like this:

10   A
dtype: object

Upvotes: 2

Views: 926

Answers (1)

jezrael
jezrael

Reputation: 862851

Use double [] for select by one element list:

print (s.loc[[10]])
10    A
dtype: object

Upvotes: 2

Related Questions