Add multiple columns to pandas dataframe from function

Given a pandas dataframe, we have to add multiple columns from function. By Pranit Sharma Last updated : October 03, 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 we are given a DataFrame with some existing columns, we know how to add a new column in a DataFrame but here, we are going to add multiple columns in the DataFrame with the help of a function.

Adding multiple columns to pandas dataframe from function

For this purpose, we are going to define a lambda function that will store some calculated values in new columns, and these new columns would be encapsulated in a list. Then we will use apply() method to apply the lambda function to the DataFrame.

Let us understand with the help of an example,

Python program to add multiple columns to pandas dataframe from function

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating DataFrame
df = pd.DataFrame({'date':['2011-01-01','2011-01-02','2011-01-03','2011-01-04']})

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

# Converting date column to datetime type
df['date'] = pd.to_datetime(df['date'])

# defining lambda function
fun = lambda x: pd.Series([x['date'].isocalendar()[1],x['date'].weekday()])

# creating new columns
df[['day', 'week']] = df.apply(fun, axis=1)

# Display modified DataFrame
print("Modified Dataframe :\n",df,"\n")


The output of the above program is:

Example: Add multiple columns to pandas dataframe from function

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.