LeetCode 题解工作台

创建新列

DataFrame employees +-------------+--------+ | Column Name | Type. | +-------------+--------+ | name | object | | salary | int. | +-------------+-----…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Create a New Column core interview pattern

bolt

答案摘要

我们可以直接计算 `salary` 的两倍,然后将结果存入 `bonus` 列。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Create a New Column core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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 列。
lightbulb

解题思路

方法一:直接计算

我们可以直接计算 salary 的两倍,然后将结果存入 bonus 列。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
import pandas as pd


def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
    employees['bonus'] = employees['salary'] * 2
    return employees
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

创建新列题解:Create a New Column cor… | LeetCode #2881 简单