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.
Suppose, we are given a DataFrame of some employee and we need to define a function that performs some operations on the data.

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 code 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:

Example: Adding a column in pandas dataframe using a function

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.