Solve LeetCode 2881 "Create a New Column" in Python with this beginner-friendly Pandas tutorial! This problem asks you to add a `bonus` column to a DataFrame, where each employee’s bonus is twice their salary. We’ll use `pandas` to create the new column in one line and return the updated DataFrame. Perfect for Python learners, data science beginners, or anyone prepping for coding interviews with Pandas!
🔍 *What You'll Learn:*
Understanding LeetCode 2881’s requirements
Adding a new column to a DataFrame with Pandas
Performing calculations on existing columns
Testing with example employee data
💻 *Code Used in This Video:*
import pandas as pd
def createBonusColumn(employees: pd.DataFrame) - pd.DataFrame:
employees['bonus'] = employees['salary'] * 2
return employees
Test case
data = [[1, "Alice", 50000], [2, "Bob", 60000], [3, "Charlie", 75000]]
df = pd.DataFrame(data, columns=["employee_id", "name", "salary"])
result = createBonusColumn(df)
print(result)
Output:
employee_id name salary bonus
0 1 Alice 50000 100000
1 2 Bob 60000 120000
2 3 Charlie 75000 150000
Test with empty DataFrame
df_empty = pd.DataFrame(columns=["employee_id", "name", "salary"])
result_empty = createBonusColumn(df_empty)
print(result_empty)
Output: Empty DataFrame with columns ["employee_id", "name", "salary", "bonus"]
🌟 *Why Solve LeetCode 2881?*
This problem teaches you how to add new columns in `pandas`—a key skill for data science and coding interviews! We’ll show how `employees['bonus'] = employees['salary'] * 2` creates a new column by doubling the `salary` values. It’s a great way to learn DataFrame manipulation, with a time complexity of O(n) where n is the number of rows. Master this, and you’ll be ready for more advanced Pandas challenges!
📚 *Who’s This For?*
Python beginners learning Pandas
Data science enthusiasts working with DataFrames
Coders prepping for data-focused interviews
👍