【发布时间】:2019-08-11 17:45:29
【问题描述】:
我有一本字典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
但我无法获得索引列表,这是我下一步所需要的。提前致谢。
【问题讨论】:
-
"我想遍历 df['name']" 不,你可能不会。那是在常规 Python 中思考,而不是 pandas 的使用方式。您想要一个可以为您提供索引的掩码
标签: python pandas dataframe indexing append