Adding a column in pandas dataframe using a function

Learn, how to add a column in pandas DataFrame using a function?
Submitted by Pranit Sharma, on November 05, 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.

A function can be defined as a block of code or an enclosed code snippet that has some special task to do and only executes when it is called. We can define a number as many functions as we want.

Problem statement

Suppose, we are given a DataFrame of some employee and we need to define a function that performs some operations on the data.

Adding a column in pandas dataframe using a function

We will add a new column to this DataFrame whose value will be computed from this function.

To add values to this function, we will declare a new column and assign it to an existing column of DataFrame calling the function we have defined. This will let the function takes all the values of the previous column one by one and calculates new values for the new column.

Let us understand with the help of an example,

Python program to add a column in pandas DataFrame using a function

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({
    'id':[101,102,103,104],
    'name':['shan','sonu','tina','raj'],
    'age':[20,21,23,20]}
    )

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

# defining a function
def fun(n):
    return n*10000

# adding new column
df['salary'] = fun(df['age'])

# Display result
print('Result:\n',df,'\n')

Output

The output of the above program is:

Example: Adding a column in pandas dataframe using a function

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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