2881 Create a New Column
Problem Statement
DataFrame employees
name
object
salary
int.
A company plans to provide its employees with a bonus.
Write a solution to create a new column name bonus
that contains the doubled values of the salary
column.
The result format is in the following example.
For the whole problem statement, please refer here.
Plans
We need the pandas library to work with DataFrames.
Create a function
createBonusColumn
that takes a DataFrame as input.Double the values in the
salary
column and save them into a new column calledbonus
.The function should return the DataFrame with the new column.
Solution
Explanation
Import pandas
We begin by importing the
pandas
library, which provides powerful tools for data manipulation and analysis.
Function Definition
We define a function named
createBonusColumn
, which takes a single argumentemployees
, expected to be a DataFrame.
Create New Column
Within the function, we create a new column called
bonus
in theemployees
DataFrame. The values for this column are calculated by taking thesalary
column and multiplying each value by 2. This is achieved using the syntaxemployees['salary'] * 2
, which leverages the ability of pandas to perform operations on entire columns efficiently.
Return the Result
Finally, the modified DataFrame, now containing the
bonus
column, is returned.
Last updated