
Sponsored
Sponsored
We can use Pandas for this task, leveraging its ability to perform operations over complete columns. Specifically, we can utilize the vectorized operation in Pandas to create a new column bonus by simply doubling the values of the existing salary column.
Time Complexity: O(n) - Where n is the number of rows in the DataFrame, as it processes each row once.
Space Complexity: O(n) - Requires additional space for the new bonus column.
1import pandas as pd
2
3# Sample DataFrame
4employees = pd.DataFrame
This Python solution uses Pandas to create a new column by applying a mathematical operation on an existing column. The multiplication operator (*) is used between the salary column and the scalar value 2, which doubles each of the salary values directly and assigns the result to a new column bonus.
In the absence of vectorized operations, we can achieve the task by iterating over each row of the DataFrame manually. However, this method is generally less efficient than vectorized operations.
Time Complexity: O(n) - It explicitly visits each row to calculate the bonus.
Space Complexity: O(n) - Holds the list of bonuses in memory before adding it as a new column.
1import pandas as pd
2
3# Sample DataFrame
4employees = pd.DataFrame({
5 'name': ['Piper', 'Grace', 'Georgia', 'Willow', 'Finn', 'Thomas'],
6 'salary': [4548, 28150, 1103, 6593, 74576, 24433]
7})
8
9# Initialize a list to store bonus values
10bonuses = []
11
12# Iterate over DataFrame rows using DataFrame.iterrows()
13for index, row in employees.iterrows():
14 # Calculate the bonus
15 bonus = row['salary'] * 2
16 # Append to the bonuses list
17 bonuses.append(bonus)
18
19# Assign the bonuses list to a new column in the DataFrame
20employees['bonus'] = bonuses
21
22print(employees)This implementation does not use vectorized operations and loops over each row of the DataFrame using the DataFrame's iterrows() method. It calculates the double salary for each employee and stores it in a list, which is then added as a new column to the DataFrame.