Home > Mobile >  How to get values from one column where another column's values match a list
How to get values from one column where another column's values match a list

Time:11-30

We have a dataframe:

      column1  column2
0        A       h
1        B       l
2        C       p

and a list:

li = ['p', 'l']

How can I use the list to look up values in column2 and return the corresponding column1 values in that order?

The desired result:

np.array(['C', 'B'])

I tried this, but it does not preserve the order:

df.loc[df['column2'].isin(li)]['column1'].values

CodePudding user response:

Set column2 as the index and use loc:

df.set_index('column2').loc[li, 'column1'].values

# array(['C', 'B'], dtype=object)

CodePudding user response:

You can do something like -

df_new = df[df['column2'].isin(li)]
df_new.index = [li.index(x) for x in df_new['column2']]
df_new = df_new.sort_index()
df_new['column1'].values
# array(['C', 'B'], dtype=object)

If you are using version 1.x of pandas - you can think of using the key argument that comes with the sort_values function like here

  • Related