2023年9月28日 星期四

9/27 每日一題(pandas 回傳第二高薪水)

Table: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id is the primary key (column with unique values) for this table.
Each row of this table contains information about the salary of an employee.

 

Write a solution to find the second highest salary from the Employee table. If there is no second highest salary, return null (return None in Pandas).

The result format is in the following example.

 

Example 1:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
Output: 
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

Example 2:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
Output: 
+---------------------+
| SecondHighestSalary |
+---------------------+
| null                | 

+---------------------+ 

import pandas as pd


def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
    res=set()
    for i,row in employee.iterrows():
        salary=row['salary']
        res.add(salary)
    res=list(res)
    res.sort()

    if len(res)<2:
        return pd.DataFrame({'SecondHighestSalary':[None]})
    else:
        return pd.DataFrame({'SecondHighestSalary':[res[-2]]})

---------------------
import pandas as pd

def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
    salaries = employee['salary'].drop_duplicates().sort_values(ascending = False)
    N = 2
    if len(salaries) < N:
        return pd.DataFrame({'SecondHighestSalary': [None]})
    else:
        ans = salaries.iloc[N-1]
        return pd.DataFrame({'SecondHighestSalary': [ans]})

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁