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

Pandas create boolean column based on equality of other columns

Is there a simple way to dynamically (!!!) create a boolean column in a Dataframe, based on the values of the other columns, by checking if the values are equal?

My DF:

df = pd.DataFrame({"column_1":[1,2,3,4,5], "column_2":[1,3,2,4,5]})

How it should look like:

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

|column_1|column_2|columns_equal|
|:-------|--------|------------:|
|     1  |     1  |    True     |
|     2  |     3  |    False    |
|     3  |     2  |    False    |
|     4  |     4  |    True     |
|     5  |     5  |    True     |

Thank you in advance 🙂

>Solution :

For the simple case of two columns you can do:

df["column_equal"] = df["column_1"] == df["column_2"]

If, instead you have more columns this will be better:

df["column_equal"] = df.eq(df["column_1"], axis=0).all(axis=1)

df.eq(df["column_1"]) will give you a new dataframe with in each column a boolean indicating if that element is the same as the one in column_1.
Then .all(axis=1) just checks if all elements in each row are 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