0
idx_list = []
for idx, row in df_quries_copy.iterrows():
    for brand in brand_name:
        if row['user_query'].contains(brand):
            idx_list.append(idx)
        else:
            continue

brand_name list looks like below

brand_name = ['Apple', 'Lenovo', Samsung', ... ] 

I have df_queries data frame which has the query the user used the table is looks like below

user_query user_id
Apple Laptop A
Lenovo 5GB B

and also I have a brand name as a list i want to find out the users who uses related with brand such as 'Apple laptop'

but when I run the script, I got a message saying that 'str' object has no attribute 'contains'

how am I supposed to do to use multiple for loop ?

Thank you in advance.


for brand in brand_name[:100]:
if len(copy_df[copy_df['user_query'].str.contains(brand)]) >0:
    ls.append(copy_df[copy_df['user_query'].str.contains(brand)].index)
    
else:continue

I tried like answer but the whole dataframe came out in a sudden as a result enter image description here

1 Answer 1

1

You can use df_quries_copy[df_quries_copy['user_query'].str.contrains(brand)].index to get index directly.

for brand in brand_name:
    df_quries_copy[df_quries_copy['user_query'].str.contrains(brand)].index

Or in your code, use brand in row['user_query'] since row['user_query'] is a string value.

Sign up to request clarification or add additional context in comments.

10 Comments

I have a quick question. no need to use iterrows to iterate the row of dataframe? I don't understand the logic even though the script is running :) and also i got a error unbalanced parenthesis at position 4
@Nini Yes, no need to iterate the dataframe. The unbalanced parenthesis might be some parenthesis is not closed.
yes, you can just put the condition what you want to filter like this, df[condition], you can read this too pandas.pydata.org/docs/getting_started/intro_tutorials/…
for brand in brand_name[:100]: print(copy_df[copy_df['user_query'].str.contains(brand)].index) the result is like below
Int64Index([], dtype='int64') Int64Index([], dtype='int64') Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], dtype='int64')
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.