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?
CodePudding user response:
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
CodePudding user response:
res = []
for i, value in enumerate(array):
if('milk' in value):
res.append(i)
CodePudding user response:
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 ")]