Find first non-null value in column

Given a pandas dataframe, we have to find the first non-null value in column.
Submitted by Pranit Sharma, on November 09, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Finding the first non-null value in column

We are given a series that has either NULL or some non-null value. We need to find the 1st row where the value is not null so that we can use this data. If the values are not null all the values are the same data type in that series.

For this purpose, we will first create a series of integer values along with some null values. We are going to use first_valid_index() method which will return that value location that has a non-null value.

Also, by applying this method inside loc[] property, we will find that particular value.

Let us understand with the help of an example,

Python code to find the first non-null value in column

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a series
s = pd.Series([np.nan,122123,np.nan])

# Display series
print('Original Series:\n',s,'\n')

# Finding first non null value
res = s.first_valid_index()

# Finding location
res_loc = s.loc[s.first_valid_index()]

# Display result
print('First non null value:\n',res_loc,'\n')

Output:

Example: Find first non-null value in column

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.