Pandas: Conditional creation of a series/dataframe column

Learn, how to create a series/dataframe column through a condition in Python? By Pranit Sharma Last updated : October 06, 2023

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.

Problem statement

Suppose that we are given the dataframe representing the marks of students. The data frame contains columns like name, age, and marks.

We need to add another column called status where we will assign the values it depends upon the values of the marks column.

Conditional creation of a series/dataframe column

For this purpose, we will first create a data frame containing three columns name, age, and marks and then we will use numpy.where() method inside which we will pass a condition.

Let us understand with the help of an example

Syntax:

numpy.where(condition, [x, y, ]/)

Let us understand with the help of an example,

Python program to create a series/dataframe column through a condition

# Import pandas
import pandas as pd

# Import numpy
import numpy as np

# Creating a dictionary
d = {
    'Name':['Ram','Shyam','Seeta','Geeta'],
    'Age':[20,20,21,21],
    'Marks':[450,479,389,400]
}

# Creating a dataframe
df = pd.DataFrame(d)

# Display original dataframe
print("Original DataFrame:\n",df,"\n")

# Add another column in df
df['Status'] = np.where(df['Marks']>=400, 'Pass', 'Fail')

# Display new df
print("New DataFrame:\n",df)

Output

The output of the above program is:

Example: Pandas: Conditional creation of a series/dataframe columnframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.