Reputation: 103
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 .loc
is 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.
Upvotes: 1
Views: 36
Reputation: 24314
Try via isin()
+loc
accessor+tolist()
:
out=df.loc[df['ID'].isin(x),'Group'].tolist()
output of out
:
[1, 9, 8]
Upvotes: 1