176. 第二高的薪水

发布时间 2023-08-12 21:02:18作者: 吾执青剑向天涯

176. 第二高的薪水

2023年8月12日19:03:40

176. 第二高的薪水

中等

SQL Schema


Pandas Schema

Employee 表:

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
在 SQL 中,id 是这个表的主键。
表的每一行包含员工的工资信息。

查询并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null(Pandas 则返回 None)

查询结果如下例所示。

示例 1:

输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

示例 2:

输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null                |
+---------------------+

这错在哪里了
奇怪的错误

import pandas as pd

def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
  employee['SecondHighestSalary'] = employee.drop_duplicates(subset=['salary']).sort_values(by="salary",ascending=False)[["salary"]]
  if(len(employee)>=2):
    return employee[['SecondHighestSalary']].iloc[1:2,[0]]
  else:
    return pd.DataFrame({"SecondHighestSalary":['null']})

我的错

import pandas as pd

def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
	employee['SecondHighestSalary'] = employee.drop_duplicates(subset=['salary']).sort_values(by="salary",ascending=False)[["salary"]]
  	if(len(employee)>=2):
    return employee[['SecondHighestSalary']].iloc[1:2,[0]]
  else:
    return pd.DataFrame({"SecondHighestSalary":[np.NaN]})

答案

import pandas as pd

def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
  	employee['SecondHighestSalary'] = employee.drop_duplicates(subset=['salary'])[["salary"]]

  	if(len(employee)>=2):
    	return employee[['SecondHighestSalary']].sort_values(by="SecondHighestSalary",ascending=False).iloc[1:2,[0]]
  	else:
    	return pd.DataFrame({"SecondHighestSalary":[np.NaN]})