Home »
Python »
Python Programs
Pandas Assigning multiple new columns simultaneously
Learn, how can we assign multiple new columns simultaneously in Python pandas?
Submitted by Pranit Sharma, on October 03, 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.
Problem statement
We are given a DataFrame with a column containing labels for each row. We are also given a dictionary with keys equal to possible labels and values equal to 2-tuples of information related to that label. We aim to create new rows for each value of the tuple in that dictionary.
Assigning multiple new columns simultaneously
For this purpose, we will first define a function where we will calculate some mathematical operations and return these operations to store them in the columns of the DataFrame to add new rows.
Let us understand with the help of an example,
Python program to assign multiple new columns simultaneously
# Importing pandas package
import pandas as pd
# Import numpy package
import numpy as np
# Defining a function
def function(arr):
return np.mean(arr), np.std(arr), np.amax(arr)
# Creating dictionary
d = {'A':[10,32,23,21,12],
'B':[0,3,3,1,2]}
# Creating DataFrame
df = pd.DataFrame(d)
# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")
# Adding new row
df[['mean', 'std', 'max']]=df[['A','B']].apply(function(np.array(df['A'])), axis=1, result_type='expand')
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »