pandas: How to get first positive number?

Viewed 850

I have a pandas dataframe like:

name    a    b    c
jack   -10  -6   -10
bill   -6   -3   -5
ray    -3   -12  -9 
pew     4   -23  -2  
shaun   12   3    2  
mitch   3    5    2

How can i make a new dataframe which takes the first positive value from each respective columns(a,b,c) and divides all the values in that column with that selected first positive value of that column and store the result of division in place of all the values. The output should look like this

name    a      b      c
jack   -10/4  -6/3   -10/2
bill   -6/4   -3/3   -5/2
ray    -3/4   -12/3  -9/2 
pew     4/4   -23/3  -2/2  
shaun   12/4   3/3    2/2  
mitch   3/4    5/3    6/2
3 Answers

Here is another way:

m=df.set_index('name')
final=m.div(m.mask(m.lt(0)).bfill().iloc[0]).reset_index()

    name     a         b    c
0   jack -2.50 -2.000000 -5.0
1   bill -1.50 -1.000000 -2.5
2    ray -0.75 -4.000000 -4.5
3    pew  1.00 -7.666667 -1.0
4  shaun  3.00  1.000000  1.0
5  mitch  0.75  1.666667  1.0

You can check which values in the dataframe are greater than 0, and take the idxmax (first True), then divide column-wise by the resulting values.

ix = df.loc[:,'a':].gt(0).idxmax()
df.loc[:,'a':] = df.loc[:,'a':].div(df.lookup(ix.values, ix.index))

   name     a         b    c
0   jack -2.50 -2.000000 -5.0
1   bill -1.50 -1.000000 -2.5
2    ray -0.75 -4.000000 -4.5
3    pew  1.00 -7.666667 -1.0
4  shaun  3.00  1.000000  1.0
5  mitch  0.75  1.666667  1.0

a/a.head(1) (pandas broadcasting should take care of the rest)

Related