使用熊猫获取与条件匹配的值的索引

时间:2019-03-20 22:00:06

标签: python pandas dataframe indexing append

我有一个字典wrong_names,一个熊猫系列df['name']和一个空列表i_list

我想遍历df['name'],如果名称在wrong_names.keys()中,我想将df中该元素的索引附加到i_list。这是我到目前为止的内容:

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

我已经看过.get_loc文档(pup是正确的参数吗?)以及这些S.O。问题:

Finding label location in a DataFrame Index

Find element's index in pandas Series

当我要求做的全部工作是将pup附加到i_list时,代码可以正常工作,所有迹象表明循环正确地标识了pup还是字典中的键,

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

但是我找不到索引列表,这是下一步所需的。预先感谢。

1 个答案:

答案 0 :(得分:2)

  • 不需要迭代。
  • 使用Series.isin进行系列的成员资格检查
  • 使用生成的掩码将df.indexconvert the result to a list.编入索引

i_list = df.index[df['name'].isin(wrong_names)].tolist()
相关问题