Predictive Hacks

How to COALESCE in Pandas

This function returns the first non-null value between 2 columns.

import pandas as pd
import numpy as np


df=pd.DataFrame({"A":[1,2,np.nan,4,np.nan],"B":['A',"B","C","D","E"]})

df
     A  B
0  1.0  A
1  2.0  B
2  NaN  C
3  4.0  D
4  NaN  E

In the following example, it will return the values of column A and if they are null, it will return the corresponding value of column B.

df['A'].combine_first(df['B'])
0    1.0
1    2.0
2      C
3    4.0
4      E

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