Search code examples
pythonrow

How do I extract values from columns of only specified rows?


I have the following table in my python:

ID name age
1 Jacob 14
2 Phil 21
3 Emil 25
4 Raj 23

How do I print column three (age) from the table but only for rows that have the element in column one that is also present in list y=[4,5,2,6]. So in this case, we are looking for the age for ID 2 and 4. I am a newbie in python, so any advice helps.

Here is what I tried so far:

C1= list(Table["ID"])
x= (list(set(C1).intersection(y)))
for x in Table["ID"]:
    print Table["age"]

I am sure that I am doing the loop wrong at the end, but I don't know how to fix it.


Solution

  • Is your data in dataframe format?

    Then instead of going through a loop, you can use the code below.

    y=[4, 5, 2, 6]
    Table[Table['ID'].isin(y)]['age']
    

    Table[Table['ID'].isin(y)] will select the rows in y