1

I have a dataframe that I want to check if it contains certain data. If anything in the dataframe column Names has store, pharmacy or str1, then I want that row of data in a different file. And everything else in another.

I want to know if there is a way to search for these strings in the dataframe. I have this line of code with a for loop inside back when I had only one string key='store', now it's a list as seen below:

key = ['store', 'pharmacy', 'str1'] #this is what I want to use now
#key = 'store' #this is what I had before

indiceName = [key in value for value in df['Names']]
subsetName = df[indiceName]
indiceStr  = [key not in row for row in df['Names']] 
subsetStr  = df[indiceStr]

Ouput looks like:

[False, False, True, True]
[True, True, False, False]

I want to keep it as that one line for loop. Is that possible? Something like:

indiceName = [key[i] in value for value in df['Names']]
indiceStr  = [key[i] not in row for row in df['Names']]
2
  • See: isin Commented Mar 8, 2022 at 18:31
  • 1
    I reopened because I realized the duplicate doesn't answer the question. Commented Mar 8, 2022 at 18:38

1 Answer 1

1

Use str.contains:

df1 = df[df["Names"].str.lower().str.contains("|".join(key))]
df2 = df[~df["Names"].str.lower().str.contains("|".join(key))]
Sign up to request clarification or add additional context in comments.

7 Comments

This is good! But I'm trying to maintain that one line for loop.
@NewTechie - You would need two loops. That is not as efficient as the above. But anyway, it would be df[df["Names"].isin([n for n in df["Names"] if all(k not in n.lower() for k in key)])]
I was thinking more along the lines like this: [[i for i in key] in row for row in df['Names']] and [[i for i in key] not in row for row in df['Names']] in order to keep the same output as before. This doesn't work, but it's the logic I'm going with.
What is wrong with the loop I suggested? What you have will not work as you want.
The only issue is that the output is not the same anymore, meaning I have make several changes throughout my script. But it's a list now and not just a single string. I might just need to do the necessary changes to get it to work with a list.
|

Your Answer

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