I am new to Python and dataframes. I have a big panda dataframe I need to extract information from, I will try to explain my problem in a small example. Say my dataframe looks like this:
name city number
Hana NYC 23
Fred London 12
Ben Paris 90
Lisa Berlin 3
Now I have a list with entries that relate to the column "number"
numbers = [3,12,23]
and I want to have the corresponding entries in another list from the "name" column
names = ['Lisa', 'Fred', 'Hana']
Is there an existing function for this problem?
CodePudding user response:
You did not explain your desired output, but:
If you want to filter by one of the cirteria:
df[df['number'].isin(numbers)]
will leave you with rows within the numbers array.
If you want both:
df[(df['number'].isin(numbers)) & (df['name'].isin(names))]
Don't forget the names array to strings:
names = ['Lisa', 'Fred', 'Hana']
CodePudding user response:
df[df.number.isin(numbers)].name.tolist()
and, if you want exactly in same order:
df[df.number.isin(numbers)].sort_values("number").name.tolist()