Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:获取每个元素的索引_Python_Pandas - Fatal编程技术网

Python 熊猫:获取每个元素的索引

Python 熊猫:获取每个元素的索引,python,pandas,Python,Pandas,我猜这是一个复制品 这是我的数据帧 WORD1 CAT1 elephant animal lion animal tiger animal hoopoe bird hornbill bird sunflower flower rose flower giraffe animal zebra animal sparr

我猜这是一个复制品

这是我的数据帧

      WORD1    CAT1   
    elephant   animal  
        lion   animal
       tiger   animal
      hoopoe    bird 
    hornbill    bird
   sunflower   flower
        rose   flower
     giraffe   animal
       zebra   animal
     sparrow    bird  
        duck   animal  
我想从“CAT1”中得到每个元素的索引

让我这样说吧

for d in data['CAT1']:
    print data[data['CAT1'] == d].index[0]
...
0
0
0
3
3
5
5
0
0
3
0
上面返回的是索引,但当存在重复项时会出现抖动。如何更正此问题?

您可以使用Python获得索引和项目:

for i, d in enumerate(data['CAT1']):
     print(i)
如果您想通过
CAT1
WORD1
中进行选择,您可以选择它们,例如:

birds = [w for w, c in zip(data['WORD1'], data['CAT1']) if c == "bird")]

注意:是一种在字符串中查找子字符串索引的方法。

如您所见,
list.index
只提供第一个索引。还不完全清楚你想要实现什么;你试过我回答中的建议了吗?@jonrharpe是的。试过了。有道理。但是我正在寻找类似的东西。那里的答案也包括了这一点,你可以使用
data['CAT1'].\u loc(d)
data[data['CAT1']==d]
对于这个问题的未来读者,你能更新以更清楚地了解你真正想要的输出吗?“从'CAT1'获取每个元素的索引”不明确。是否要在
CAT1
中为每个不同条目指定第一个索引,还是要为每个不同条目分配一个编号并用该编号替换文本?