127

Is there any way to access the first element of a Series without knowing its index?

Let's say I have the following Series:

import pandas as pd

key='MCS096'
SUBJECTS = pd.DataFrame(
    {
        "ID": pd.Series([146], index=[145]),
        "study": pd.Series(["MCS"], index=[145]),
        "center": pd.Series(["Mag"], index=[145]),
        "initials": pd.Series(["MCS096"], index=[145]),
    }
)

Print out SUBJECTS:

print(SUBJECTS[SUBJECTS.initials==key]['ID'])
>>> 145    146
>>> Name: ID, dtype: int64

How can I get the value 146 here without using index 145?

rachwa
  • 1,805
  • 1
  • 14
  • 17
Hello lad
  • 17,344
  • 46
  • 127
  • 200

1 Answers1

201

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • 1
    How is this done with a Series rather than a DataFrame. Do we have to convert the Series first? – sobrio35 Jan 05 '20 at 22:29
  • Sorry, I was using this in another project and ```df['A'].iloc[0]``` gave me an error but ```df.iloc[0]['A']``` did not for some reason. – sobrio35 Jan 05 '20 at 22:41
  • @sobio35 yes, that should actually not work, because `df['A']` creates a Series and on this iloc won't work. But the other way around, as described by you, it works, as iloc is performed on the whole df and then Series ['A'] is selected. – Generic Wevers Oct 09 '20 at 12:16
  • if you want to do this with a series you can also do: `ser.reset_index(drop=True,inplace=True)` ; `ser[0]` – robbwh Jul 20 '21 at 23:54
  • @GenericWevers Why do you think `iloc` doesn't work on a `Series`? In this particular answer there is an example where it does. – Antony Hatchkins Dec 08 '21 at 06:49
  • @AntonyHatchkins At the time I tried it didn't work. I tried today and your right. – Generic Wevers Jan 13 '22 at 13:16
  • This will only work as long as the DataFrame/Series is not empty. Any suggestion on making it "null resistant", without a helper variable? – Andor Jun 09 '23 at 10:22