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

How to transform dataframe to binary based on values being above/below the row median (if > median, 1, else 0)?

I am looking to transform a dataframe to binary based on row median. Please see my input and expected output below.

import pandas as pd
df_input = pd.DataFrame({'row1': [5, 10, 20], 'row2': [1, 30, 40],},
                        index = ['2021-02-24', '2021-02-25', '2021-02-26'])
df_expected_output = pd.DataFrame({'row1': [1, 0, 0], 'row2': [0, 1, 1],},
                        index = ['2021-02-24', '2021-02-25', '2021-02-26'])
df_median = df_input.median(axis=1)

I found this elegant solution for transforming based on column median here but could not get it to work for comparing rows.

(dat > dat.median()).astype('int')

How can I do this for rows?

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

>Solution :

Use gt with the correct axis:

df_input.gt(df_input.median(axis=1), axis=0).astype(int)

output:

            row1  row2
2021-02-24     1     0
2021-02-25     0     1
2021-02-26     0     1
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