Shijo
Shijo

Reputation: 9711

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

Upvotes: 4

Views: 1854

Answers (2)

BENY
BENY

Reputation: 323326

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

Upvotes: 5

cs95
cs95

Reputation: 402814

You could assign values to df.values, this should be really fast.

v = df.values
v[v.argmin(0), np.arange(len(v))] = newvalues
df[:] = v

df     
          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

Upvotes: 4

Related Questions