Reputation: 11
I have an array and I need to get the index of the elements which contain the word "milk".
array = ["bread ciabatta", "milk natural", "milk chocolate", "cookies chocolate", "bread banana", "bread focaccia", "milk strawberry"]
How can I accomplish this?
Upvotes: 0
Views: 658
Reputation: 15913
One of the ways is to use enumerate
inside a list-comprehension
:
array = ["bread ciabatta", "milk natural", "milk chocolate", "cookies chocolate", "bread banana", "bread focaccia", "milk strawberry"]
indices = [i for i, s in enumerate(array) if 'milk' in s]
print(indices) # output [1, 2, 6]
Learn about enumerate
: Docs
Upvotes: 4
Reputation: 1123
res = []
for i, value in enumerate(array):
if('milk' in value):
res.append(i)
Upvotes: 2
Reputation: 2691
import pandas as pd
array = pd.Series(["bread ciabatta", "milk natural", "milk chocolate", "cookies chocolate", "bread banana", "bread focaccia", "milk strawberry"])
array.str.match(r".*milk ")
This returns a boolean mask.
If you need indices you can do:
array.index[array.str.match(r".*milk ")]
Upvotes: 1