2881. 创建新列
2881. 创建新列
题目
DataFrame
employees+-------------+--------+ | Column Name | Type. | +-------------+--------+ | name | object | | salary | int. | +-------------+--------+
A company plans to provide its employees with a bonus.
Write a solution to create a new column name bonus that contains the doubled values of the salary column.
The result format is in the following example.
Example 1:
Input:
DataFrame
employees+---------+--------+ | name | salary | +---------+--------+ | Piper | 4548 | | Grace | 28150 | | Georgia | 1103 | | Willow | 6593 | | Finn | 74576 | | Thomas | 24433 | +---------+--------+Output:
+---------+--------+--------+ | name | salary | bonus | +---------+--------+--------+ | Piper | 4548 | 9096 | | Grace | 28150 | 56300 | | Georgia | 1103 | 2206 | | Willow | 6593 | 13186 | | Finn | 74576 | 149152 | | Thomas | 24433 | 48866 | +---------+--------+--------+Explanation:
A new column bonus is created by doubling the value in the column salary.
题目大意
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 | 6593 | 13186 | | Finn | 74576 | 149152 | | Thomas | 24433 | 48866 | +---------+--------+--------+解释:
通过将 salary 列中的值加倍创建了一个新的 bonus 列。
解题思路
解题思路
利用 Pandas 的直接列操作功能,可以高效地向 DataFrame 添加新列,此功能允许我们基于现有列的值进行计算,并将结果赋值给新列。
新增列:
- 使用
employees['bonus']为DataFrame添加新列。如果该列已存在,则会覆盖原值。 - 通过
employees['salary'] * 2进行逐元素计算,生成新列的值。
- 使用
返回 DataFrame:
- 新增列后,原
DataFrame被修改(Pandas默认行为是就地操作DataFrame),并作为结果返回。
- 新增列后,原
复杂度分析
- 时间复杂度:
O(n),其中n是 DataFrame 的行数,新增bonus列需要逐元素计算操作。 - 空间复杂度:
O(n),新增的bonus列需要额外的存储空间。
代码
import pandas as pd
def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
employees['bonus'] = employees['salary'] * 2
return employees
