Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get a single value from dataframe only in Python

I have dataframe df_my that looks like this

      id    name        age     major
----------------------------------------
0     1     Mark        34      English
1     2     Tom         55      Art
2     3     Peter       31      Science
3     4     Mohammad    23      Math
4     5     Mike        47      Art
...

I am trying to get the value of major (only)

I used this and it works fine when I know the id of the record

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df_my["major"][3]

returns

"Math"

great

but I want to get the major for a variable record

I used

i = 3
df_my.loc[df_my["id"]==i]["major"]

and also used

i = 3
df_my[df_my["id"]==i]["major"]

but they both return

3     Math

it includes the record index too

how can I get the major only and nothing else?

>Solution :

You could use squeeze:

i = 3
out = df.loc[df['id']==i,'major'].squeeze()

Another option is iat:

out = df.loc[df['id']==i,'major'].iat[0]

Output:

'Science'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading