2

I have a dictionary wrong_names, a pandas series df['name'], and an empty list i_list.

I want to iterate through df['name'], and if the name is in wrong_names.keys(), I want to append the index of that element in df to i_list. Here is what I have so far:

i_list = []
for pup in df['name']:
    if pup in wrong_names.keys():
    i_list.append(df.index.get_loc(pup))
i_list

I have already looked at .get_loc documentation (is pup the right argument?), as well as these S.O. questions:

Finding label location in a DataFrame Index

Find element's index in pandas Series

The code works fine when all I ask it to do is append pup to i_list, by all indications the loop correctly identifies when the pup is also a key in the dictionary,

i_list = []
for pup in df['name']:
    if pup in wrong_names.keys():
    i_list.append(pup)
i_list

but I can't get a list of the indices, which is what I need for the next step. Thanks in advance.

cs95
  • 379,657
  • 97
  • 704
  • 746
a2fet
  • 37
  • 1
  • 6
  • 1
    "I want to iterate through df['name']" no you probably do not. That is thinking in regular Python and not how pandas is intended to be used. You want a mask that gives you the indices – roganjosh Mar 20 '19 at 22:01

1 Answers1

6
  • No iteration needed.
  • Use Series.isin for membership checks on Series
  • Use the resultant mask to index into df.index and convert the result to a list.

i_list = df.index[df['name'].isin(wrong_names)].tolist()
cs95
  • 379,657
  • 97
  • 704
  • 746