1

From the table below, I have a list x =[2,2,4] (x contains some of the value from the ID column). My task is to use the list x and make a new list , y, that contains some values from df["group"]. So in this case the answer would be y=[1,9,8]

df=(tabulate({'ID': [1, 2, 2, 4], 'Age': [4, 15, 18, 6], 'Group': [3, 1, 9, 8], 'Color':['R', 'BL', 'G', 'G'] }, headers="keys", tablefmt='fancy_grid', missingval='N/A'))
ID Age Group Color
1 4 3 R
2 50 1 BL
2 18 9 G
4 6 8 G

My approach: I know .locis used for things like this. So I tried doing:

y=[]
mask= x == df["ID"] 
y= (df.loc[mask, "group"])
print(y)

This unfortunately didn't work. I am quite stuck and don't know what to do next. Any help is appreciated.

1
  • seems like pandas question and dataframe from pypi Commented Aug 13, 2021 at 5:10

1 Answer 1

1

Try via isin()+loc accessor+tolist():

out=df.loc[df['ID'].isin(x),'Group'].tolist()

output of out:

[1, 9, 8]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.