简体   繁体   中英

Matching two lists of nonequivalent length and appending matches to new list

I have 2 lists and a DF: Indiana Zip Codes, Ohio Zip Codes, and gift purchaser zip codes (the data frame). There are 348 Indiana zip codes, 227 Ohio zip codes, and 6,000 purchaser zip codes (some of which are not Ohio or Indiana based)

I want to find all the matching zip codes in the purchaser dataframe and see if there is a match to any zip codes in indiana or ohio zip code list, if there is then append the entire row of the purchaser list to the respective state list

purchaser_zip = purchasers['zip']
indiana_zip = indiana['zip']
ohio_zip = ohio['zip']

ohio_match = []
indiana_match = []

for i in purchaser_zip:
    if i == indiana_zip.any():
        indiana_match.append(i)

for i in purchaser_zip:
    if i == ohio_zip.any():
        ohio_match.append(i)

I would use the join method, but these are lists of unequal length. And I am only returned with an empty list

You can use isin :

indiana_match = purchasers[purchasers['zip'].isin(indiana_zip)]
ohio_match = purchasers[purchasers['zip'].isin(ohio_zip)]

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