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

Check if there is any repeated element in a dataframe (excluding empty cells)

Hi I am trying to get "True" as output if there is a repeated element in a dataframe, and "False" if there is no repeated element. This should not take the empty cells into account.

Example 1:

import pandas as pd
data_df = {'col1': ['A','B', 'C', 'D'],

           'col2': ['E','F', '', 'G'],

           'col3': ['H', '', '  ', '  ']}

df = pd.DataFrame(data_df)

enter image description here

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

Should display "False"

Example 2:

enter image description here

Should display "True"

Example3:

enter image description here

Should display "True"

>Solution :

You can use:

out = (df.stack()  # stack to Series, removing NaNs
         # remove empty/space strings
         .loc[lambda s: s.str.strip().ne('')]
         # is there any duplicate?
         .duplicated().any()
      )

Outputs:

False
True
True
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