Home > front end >  how to get a single value from dataframe only in Python
how to get a single value from dataframe only in Python

Time:04-27

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

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?

CodePudding user response:

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'
  • Related