Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Replace minimum values with a list of values - rowise

I have a dataframe which has numbers in all column's. I would like to find the minimum value of each column and replace them with a given set of values. I tried idxmin with iloc, but no luck , may be I'm using them in the wrong way. Any help is appreciated.

df = abs(pd.DataFrame(np.random.randn(4, 4)))
print (df)
print (df[df!=0].min(axis=0))
newvalues =[1,2,3,4]

Lets say the input is

          0         1         2         3
0  2.776975  1.433614  0.147925  0.032635
1  1.328099  0.050764  0.255676  0.360205
2  0.614594  0.547384  0.791848  0.340333
3  1.475486  0.114053  0.904416  0.060585

Expected Output would be

          0         1         2         3
0  2.776975  1.433614         3         4
1  1.328099         2  0.255676  0.360205
2         1  0.547384  0.791848  0.340333
3  1.475486  0.114053  0.904416  0.060585
like image 572
Shijo Avatar asked Jan 04 '23 04:01

Shijo


1 Answers

By using mask, eq, mul

df.mask(df.eq(df.min(0),1),df.eq(df.min(0),1).mul([1,2,3,4]))
Out[41]: 
          0         1         2         3
0  2.776975  1.433614  3.000000  4.000000
1  1.328099  2.000000  0.255676  0.360205
2  1.000000  0.547384  0.791848  0.340333
3  1.475486  0.114053  0.904416  0.060585

Or np.putmask

v=df.values
np.putmask(v, v==np.min(v,0), [1,2,3,4])
df
Out[72]: 
          0         1         2         3
0  2.776975  1.433614  3.000000  4.000000
1  1.328099  2.000000  0.255676  0.360205
2  1.000000  0.547384  0.791848  0.340333
3  1.475486  0.114053  0.904416  0.060585
like image 173
BENY Avatar answered Jan 29 '23 11:01

BENY