2881 Create a New Column

Problem Statement

DataFrame employees

Column NameType.

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 called bonus.

  • The function should return the DataFrame with the new column.

Solution

import pandas as pd

def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
    # Create a new column 'bonus' which is twice the value of the 'salary' column
    employees['bonus'] = employees['salary'] * 2

    # Return the updated dataframe
    return employees

Explanation

  1. Import pandas

    • We begin by importing the pandas library, which provides powerful tools for data manipulation and analysis.

  2. Function Definition

    • We define a function named createBonusColumn, which takes a single argument employees, expected to be a DataFrame.

  3. Create New Column

    • Within the function, we create a new column called bonus in the employees DataFrame. The values for this column are calculated by taking the salary column and multiplying each value by 2. This is achieved using the syntax employees['salary'] * 2, which leverages the ability of pandas to perform operations on entire columns efficiently.

  4. Return the Result

    • Finally, the modified DataFrame, now containing the bonus column, is returned.

Last updated