ADVERTISEMENT
ADVERTISEMENT

How to apply Pandas function to column to create multiple new columns?

Given a Pandas DataFrame, we have to apply pandas function to columns to create multiple new columns.
Submitted by Pranit Sharma, on May 18, 2022

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Here, we are going to learn how to apply a function to a column to create multiple columns.

For this purpose, we are going to define a function that will return multiple values, we will then zip these multiple values and map them into multiple columns in a DataFrame.

Here, we are going to use zip() function, below is the syntax:

zip('object_1','object_2',.....,'object_n')

The zip() function is used to return zipped objects, it contains an iterator, and one by one it passes a value and pairs them.

Also, we are going to map function, which is used to map multiple values, here we will use the map function to call our defined function for getting multiple values the multiple values and the column of DataFrame will be joined together by zip() function.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example.

# Importing Pandas package
import pandas as pd

# Create a dictionary
d= {'Num': [ i for i in range(10)]}

# Create DataFrame
df1 = pd.DataFrame(d)

# Display DataFrame
print("Original DataFrame:\n",df1,"\n")

# Defining a function
def function(n):
     return n, n*10, n*20, n*30, n*40, n*50

# Making 6 new columns and zipping all the 6 values 
# coming from function into these columns
df1['N1'],df1['N2'],df1['N3'],df1['N4'],df1['N5'],df1['N6'] = zip(*df1['Num'].map(function))

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

Output:

Example: Apply Pandas function to column

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.