We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Modify Columns

Difficulty: Easy


Problem Description

A company intends to give its employees a pay rise. Write a solution to modify the salary column by multiplying each salary by 2.


Key Insights

  • The task requires modifying a specific column in a DataFrame.
  • The operation is a straightforward multiplication of each salary by a constant factor (2).
  • The problem can be solved using vectorized operations in DataFrame libraries like pandas.

Space and Time Complexity

Time Complexity: O(n) - where n is the number of employees (rows in the DataFrame). Space Complexity: O(1) - as we are modifying the existing DataFrame in place.


Solution

To solve this problem, we will use a DataFrame, which is a suitable data structure for storing tabular data. The algorithm involves iterating through the salary column and applying the multiplication operation. In Python, this can be efficiently handled using libraries like pandas, which allow for vectorized operations, meaning we can apply the operation to the entire column at once without explicitly iterating through each row.


Code Solutions

import pandas as pd

# Sample DataFrame creation
data = {
    'name': ['Jack', 'Piper', 'Mia', 'Ulysses'],
    'salary': [19666, 74754, 62509, 54866]
}
employees = pd.DataFrame(data)

# Modify salary by multiplying each salary by 2
employees['salary'] = employees['salary'] * 2

# Output the modified DataFrame
print(employees)
← Back to All Questions