Reputation: 18638
I guess this is a duplicate of Find element's index in pandas Series .
This is my dataframe;
WORD1 CAT1
elephant animal
lion animal
tiger animal
hoopoe bird
hornbill bird
sunflower flower
rose flower
giraffe animal
zebra animal
sparrow bird
duck animal
I would like to get the index of each element from 'CAT1';
Let me put it this way;
for d in data['CAT1']:
print data[data['CAT1'] == d].index[0]
...
0
0
0
3
3
5
5
0
0
3
0
The above returns the index, but falters when there are duplicates. How do I get this rectified?
Upvotes: 0
Views: 412
Reputation: 121974
You can enumerate
in Python to get the indices along with the items:
for i, d in enumerate(data['CAT1']):
print(i)
If you want to select from WORD1
by CAT1
, you could zip
them, for example:
birds = [w for w, c in zip(data['WORD1'], data['CAT1']) if c == "bird")]
Note: str.index
is a method for finding the index of a sub-string within a string.
Upvotes: 1