-1

I have 2 dataframes as such:

dfA=pd.DataFrame([[1,2,3],[4,5,6]])
dfB=pd.DataFrame([[True,False,False],[False,True,False]])

How do i create a new dataframe where based on the same index,

2 ** (dfA+1) only if dfB is true 
2 ** (dfA) only if dfB is false. 

What I like to achieve is a dataframe as such:

df_output = pd.DataFrame([[4,4,8],[16,64,64]])

Thanks!

0

1 Answer 1

1

You can use DataFrame.mask:

(2 ** dfA).mask(dfB, 2 ** (dfA+1))
Out: 
    0   1   2
0   4   4   8
1  16  64  64

This will check dfB, if True, take the values from the original DataFrame ((2 ** dfA)) and if false, take the values from the other (2 ** (dfA+1)).

This is similar to numpy's where function:

np.where(dfB, 2 ** (dfA+1), 2 ** (dfA))
Out: 
array([[ 4,  4,  8],
       [16, 64, 64]])

However, it loses the index and columns so you may need to wrap the result in a DataFrame constructor:

pd.DataFrame(np.where(dfB, 2 ** (dfA+1), 2 ** (dfA)), dfA.index, dfA.columns)
Out: 
    0   1   2
0   4   4   8
1  16  64  64
Sign up to request clarification or add additional context in comments.

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.