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: replace values in rows according to their amount

I have a dataframe as follows,

import pandas as pd

d ={'col1': [1, 2, 5], 'col2': [3, 4, 2], 'col3': [5, 1, 3]}
data = pd.DataFrame(d)

I would like to replace the max value with ‘max’, the min value with ‘min’ and the mid value (remaining value) with ‘mid’ in row-wise fashion.
I have done the following:

data.apply(lambda row: row.replace(min(row),'min').replace(max(row), 'max').replace(r'\d+', 'mid', regex=True).astype('str'), axis=1)

while it works for min and max value, it does not work for mid value, but I am not sure what i am doing wrong.

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 numpy.select for comapre max and min per columns and if values no match is assigned mid text:

arr = np.select([data.eq(data.max(axis=1), axis=0),
                 data.eq(data.min(axis=1), axis=0)], ['max', 'min'], 'mid')

df1 = pd.DataFrame(arr, index=data.index, columns=data.columns)
print (df1)
  col1 col2 col3
0  min  mid  max
1  mid  max  min
2  max  min  mid

Your code working if first convert to strings:

df1 = data.apply(lambda row: row.replace(min(row),'min').replace(max(row), 'max').astype('str').replace(r'\d+', 'mid', regex=True), axis=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