简体   繁体   中英

matching rows to list of values in python

I have a 23 column dataframe where one of the columns called column_lei contain the LEIs of various companies, I also have a list called lei_codes which contains loads of specific LEIs which i need to find in the dataframe.

How could i run the list through each row in the lei column in the dataframe and if there is a match within any of the rows in that column to any of the values in the list for that entire row in the dataframe to be picked out and placed into a new dataframe. So at the end i have a new dataframe which contains all 23 columns of records where there was a match on the LEI column against the list.

You can use the function isin() on the column "column_lei"

Here an example with 3 columns:

import pandas as pd
import numpy as np

df = pd.DataFrame({"a": np.repeat("a", 5),
                   "column_lei": [1,2,3,4,5],
                   "b": np.repeat("b", 5)})
lei_codes = [1,3,5]
df_new = df[df.column_lei.isin(lei_codes)]
df_new

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM