Description

Pandas Schema

data = [[1, 'A', 'm', 2500], [2, 'B', 'f', 1500], [3, 'C', 'm', 5500], [4, 'D', 'f', 500]]
salary = pd.DataFrame(data, columns=['id', 'name', 'sex', 'salary']).astype({'id':'Int64', 'name':'object', 'sex':'object', 'salary':'Int64'})


Table: Salary

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| id          | int      |
| name        | varchar  |
| sex         | ENUM     |
| salary      | int      |
+-------------+----------+
id is the primary key (column with unique values) for this table.
The sex column is ENUM (category) value of type ('m', 'f').
The table contains information about an employee.

Write a solution to swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a single update statement and no intermediate temporary tables.

Note that you must write a single update statement, do not write any select statement for this problem.

The result format is in the following example.

Example 1:

  • Input:
      Salary table:
      +----+------+-----+--------+
      | id | name | sex | salary |
      +----+------+-----+--------+
      | 1  | A    | m   | 2500   |
      | 2  | B    | f   | 1500   |
      | 3  | C    | m   | 5500   |
      | 4  | D    | f   | 500    |
      +----+------+-----+--------+
      
  • Output:
      +----+------+-----+--------+
      | id | name | sex | salary |
      +----+------+-----+--------+
      | 1  | A    | f   | 2500   |
      | 2  | B    | m   | 1500   |
      | 3  | C    | f   | 5500   |
      | 4  | D    | m   | 500    |
      +----+------+-----+--------+
      
  • Explanation:
    (1, A) and (3, C) were changed from ‘m’ to ‘f’.
    (2, B) and (4, D) were changed from ‘f’ to ‘m’.

Submitted Code

import pandas as pd

def swap_salary(salary: pd.DataFrame) -> pd.DataFrame:
    salary['sex'] = salary['sex'].map({'m': "f", 'f': 'm'})
    return salary

Runtime: 254 ms | Beats 73.14%
Memory: 66.45 MB | Beats 69.80%

map()을 사용해서 m → f 또는 f → m 으로 매핑하고, 새로운 데이터프레임 생성 없이 원본을 수정했다.

Other Solutions

1st

def swap_salary(salary: pd.DataFrame) -> pd.DataFrame:
    swap = lambda x: 'm' if x == 'f' else 'f'
    salary['sex'] = salary.sex.apply(swap)
    return salary

apply()를 사용하는 방법도 있다.

2nd

UPDATE salary SET sex =   -- 1. 테이블의 각 행에 대해 sex열의 값을 업데이트 시작
CASE sex                  -- 2. sex열의 현재 값을 기준으로 조건 판단
    WHEN 'm' THEN 'f'       -- 'm'이면 새 값으로 'f'
    ELSE 'm'                -- 'm'이 아니면 새 값으로 'm'
END;                        -- CASE문 종료

다른 임시 테이블 생성 없이, UPDATE를 한 번만 수행해야하는 조건에 맞는 코드다.

Leave a comment