1

When comparing two dataframes and putting the result back into a dataframe:

dfA = pd.DataFrame({'Column':[1,2,3,4]})

or in human readable form:

    Column
0   1
1   2
2   3
3   4

dfB = pd.DataFrame({'Column':[1,2,4,3]})

or in human readable form:

    Column
0   1
1   2
2   4
3   3

pd.DataFrame(dfA > dfB)

pandas outputs a dataframe with true or false values.

    Column
0   False
1   False
2   False
3   True

Is it possible to change the name from 'true' or 'false' to 'lower' or 'higher'? I want to know if the outcome is higher, lower or equal, that is why I ask. If the output is not higher or lower, (true or false) then it must be equal.

2 Answers 2

2

You may use map:

In [10]: pd.DataFrame(dfA > dfB)['Column'].map({True: 'higher', False: 'lower'})
Out[10]:
0     lower
1     lower
2     lower
3    higher
Name: Column, dtype: object
Sign up to request clarification or add additional context in comments.

2 Comments

This is an interesting approach, would this method be able to work with several columns at the same time. Like when comparing dataframes with multiple columns? + How would I include is neither higher or lower, but equal to this method?
I add to your solution according to [stackoverflow.com/questions/39109045/…. So, you gave the right answer for my case. But you need to add the ternary solution here.
1

I'd recommend np.where for performance/simplicity.

pd.DataFrame(np.where(dfA > dfB, 'higher', 'lower'), columns=['col'])

      col
0   lower
1   lower
2   lower
3  higher

You can also nest conditions if needed with np.where,

m1 = dfA > dfB
m2 = dfA < dfB  
pd.DataFrame(
    np.where(m1, 'higher', np.where(m2, 'lower', 'equal')),
    columns=['col']
)

Or, follow a slightly different approach with np.select.

pd.DataFrame(
    np.select([m1, m2], ['higher', 'lower'], default='equal'),
    columns=['col']
)

      col
0   equal
1   equal
2   lower
3  higher

2 Comments

I used a ternary as suggested here: [stackoverflow.com/questions/39109045/…
@nappingkid cut is an interesting solution. The ternery you mention is much like what is in my answer here.

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.