0

I have a list in Python and I have a dataframe of values I want to transform them into:

fruits = ["cherry", "strawberry", "grape"]
name code
cherry s1
strawberry s2
apple s3
grape s4

I would like to create a new list so that I achieve

newlist = ["s1", "s2", "s4"]

How would I do this in Python?

mbenoo
  • 7
  • 1

1 Answers1

0

Let's try using .isin and loc -

newlist = list(df.loc[df['name'].isin(fruits),'code'])
print(newlist)
['s1', 's2', 's4']

df['name'].isin(fruits) returns a boolean to check if the fruits in your list match with the columns. df.loc allow you to filter by those fruits and returns the values in column code

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51