LeetCode 题解工作台

修改列

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

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Modify Columns core interview pattern

bolt

答案摘要

import pandas as pd def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Modify Columns core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

一家公司决定增加员工的薪水。

编写一个解决方案,将每个员工的薪水乘以2来 修改 salary 列。

返回结果格式如下示例所示。

 

示例 1:

输入:
DataFrame employees
+---------+--------+
| name    | salary |
+---------+--------+
| Jack    | 19666  |
| Piper   | 74754  |
| Mia     | 62509  |
| Ulysses | 54866  |
+---------+--------+
输出:
+---------+--------+
| name    | salary |
+---------+--------+
| Jack    | 39332  |
| Piper   | 149508 |
| Mia     | 125018 |
| Ulysses | 109732 |
+---------+--------+
解释:
每个人的薪水都被加倍。
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
import pandas as pd


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

复杂度分析

指标
时间complexity is O(n) where n is the number of rows, due to column-wise operations. Space complexity is O(1) extra space if done in place, otherwise O(n) for creating a new column copy.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Emphasize vectorized column operations.

  • question_mark

    Check if the candidate avoids unnecessary loops.

  • question_mark

    Look for correct preservation of DataFrame structure.

warning

常见陷阱

外企场景
  • error

    Using explicit for-loops over rows, which is slower.

  • error

    Accidentally modifying other columns or changing row order.

  • error

    Forgetting to return or assign the updated DataFrame.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Multiply by a different constant or apply another arithmetic operation.

  • arrow_right_alt

    Modify multiple numeric columns at once using the same pattern.

  • arrow_right_alt

    Apply a conditional update only to certain rows based on a filter.

help

常见问题

外企场景

修改列题解:Modify Columns core int… | LeetCode #2884 简单