LeetCode 题解工作台
创建新列
DataFrame employees +-------------+--------+ | Column Name | Type. | +-------------+--------+ | name | object | | salary | int. | +-------------+-----…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Create a New Column core interview pattern
答案摘要
我们可以直接计算 `salary` 的两倍,然后将结果存入 `bonus` 列。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Create a New Column core interview pattern 题型思路
题目描述
DataFrame employees
+-------------+--------+
| Column Name | Type. |
+-------------+--------+
| name | object |
| salary | int. |
+-------------+--------+
一家公司计划为员工提供奖金。
编写一个解决方案,创建一个名为 bonus 的新列,其中包含 salary 值的 两倍。
返回结果格式如下示例所示。
示例 1:
输入: DataFrame employees +---------+--------+ | name | salary | +---------+--------+ | Piper | 4548 | | Grace | 28150 | | Georgia | 1103 | | Willow | 6593 | | Finn | 74576 | | Thomas | 24433 | +---------+--------+ 输出: +---------+--------+--------+ | name | salary | bonus | +---------+--------+--------+ | Piper | 4548 | 9096 | | Grace | 28150 | 56300 | | Georgia | 1103 | 2206 | | Willow | 593 | 13186 | | Finn | 74576 | 149152 | | Thomas | 24433 | 48866 | +---------+--------+--------+ 解释: 通过将 salary 列中的值加倍创建了一个新的 bonus 列。
解题思路
方法一:直接计算
我们可以直接计算 salary 的两倍,然后将结果存入 bonus 列。
时间复杂度 ,空间复杂度 。
import pandas as pd
def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
employees['bonus'] = employees['salary'] * 2
return employees
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate uses direct assignment to create the new column.
- question_mark
The candidate understands DataFrame manipulation with methods like `assign()` or `apply()`.
- question_mark
The candidate demonstrates knowledge of computational complexity in the context of DataFrame operations.
常见陷阱
外企场景- error
Incorrectly assigning the new column without ensuring it calculates the correct value.
- error
Not handling edge cases such as missing or negative salary values.
- error
Misunderstanding the DataFrame assignment syntax, leading to errors or incorrect results.
进阶变体
外企场景- arrow_right_alt
Calculate the bonus as a percentage of the salary (e.g., 150% of salary).
- arrow_right_alt
Create a column based on a different type of calculation, such as applying a tax rate.
- arrow_right_alt
Work with a larger dataset and implement efficient methods for column operations.