1

I have the following dataframe:

    limit1  limit2 
a    123     567
b    65      0
c    123     1233
d    0987    0
e    231451  0998

I want to create a new frame with the lower limit for each row. Except when there is a 0, in which case the value from the other column is taken.

desired output:

    limit1  limit2
a    123     567
b    65      65
c    123     1233
d    0987    0987
e    231451  0998

As you can see the 0 on the right are replaced with the value from the corresponding row from the left.

My following code does not work:

low_limit = pd.concat([limit1, limit2], join='outer', axis=1)
if limit2 == 0:
    low_limit = limit1
else:
    low_limit.min(axis=1).dropna()

the error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
4

2 Answers 2

1

Use np.where(condition, outcome if condition is True, outcome ifcondition false)

df['limit2']=np.where(df.limit2==0,df.limit1,df.min(1))

    limit1  limit2
a     123     123
b      65      65
c     123     123
d     987     987
e  231451     998
Sign up to request clarification or add additional context in comments.

Comments

0

So you can do replace since min(NaN, not NaN value) out put the not null value

df.limit2 = df.replace({'limit2' : {0 : np.nan}}).min(axis=1)
df
Out[46]: 
   limit1  limit2
a     123   123.0
b      65    65.0
c     123   123.0
d     987   987.0
e  231451   998.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.