Predictive Hacks

How to Combine DataFrames: Merging Values In One Column

There is a nice trick for showing two values in one cell in a data frame, which can provide a clearer view. For example, this can be useful when we want to show the values of a column and their ranks in a single cell.

Let’s suppose we have the following dataframe:

import pandas as pd
from IPython.display import display_html

df=pd.DataFrame({'A':[2.2,2.1,3.1,1.2,2.0],'B':[2.7,2.1,1.4,5.2,2.2]})

Let’s show how we can show both the values and the rank of these columns:

def combine_with_color(val1, val2):
    return f'<span style="color: red">{val1}</span>/<span style="color: blue">{val2}</span>'

combined = pd.DataFrame(index=df1.index, columns=df1.columns)
for col in df1.columns:
    combined[col] = [combine_with_color(df1.loc[idx, col], df2.loc[idx, col]) for idx in df1.index]

combined_html = combined.tail(30).to_html(escape=False)
display_html(combined_html, raw=True)

What we did was create an HTML representation of the values for every cell as shown below:

Then, using the to_html function of the pandas dataframe, we can transform it into HTML and show it using display_html.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s