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

Within a DataFrame, check a column for substring and return new columns with values?

Hello this is my dataframe with 2 columns:

ID      CODES
36233   LEH,PW
6175    N/A
6242    
6680    MS,XL,JFK

In column CODES, I need to identity the comma (",") and then count the number of commas and return it in a dataframe:

Output:

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

ID      CODES   HAS COMMA   NO. OF COMMAS
36233   LEH,PW  TRUE        1
6175    N/A     FALSE       0
6242            FALSE       0
6680  MS,XL,JFK TRUE        3

So far i’ve tried DF['HAS COMMA'] = np.where(DF['CODE'].str.contains(','),True, False) but this returns TRUE where there are blanks. 🙁

Additionally DF['NO OF COMMAs']=DF['CODE'].count(",") returns an error.

Thank you!!!

>Solution :

How about with:

df['HAS COMMA'] = df.CODES.str.contains(',').fillna(False)
df['NO. OF COMMA'] =  df.CODES.str.count(',').fillna(0)

prints:

      ID      CODES  HAS COMMA  NO. OF COMMA
0  36233     LEH,PW       True           1.0
1   6175        N/A      False           0.0
2   6242        NaN      False           0.0
3   6680  MS,XL,JFK       True           2.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