Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate the presence of a single string within another string

By using the following code I am trying to only keep the rows from the dataset that contain the value 9 within Col_B which is a string.

The issue is that by using this code it returns ONLY the rows that consist of ONLY the string "9",
while I want to also keep the rows that contain 9 amongst other strings.

Original input:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   Col_A        Col_B
0      5  1,2,9,0,6,4
1      2        3,1,0
2     46            0
3    184        1,5,7
4     31            9
5     81          9,0

Code used:

desired_numbers = ['9,', ',9', ',9,', '9']
df1 = df1[df1['Col_B'].isin(desired_numbers)]
df1

Original output:

   Col_A  Col_B
0     31      9

Desired output:

   Col_A        Col_B
0      5  1,2,9,0,6,4
1     31            9
2     81          9,0

Please let me know if you have any recommendations! Thanks

>Solution :

Try with string str.contains

out = df[df.Col_B.str.contains(r'\b9\b')] #str.match also work

Out[336]: 
   Index  Col_A        Col_B
0      0      5  1,2,9,0,6,4
4      4     31            9
5      5     81          9,0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading