[코딩테스트]/[Pandas]

[LeetCode - Pandas] (Easy) 1527. Patients With a Condition

잰잰' 2025. 4. 15. 12:15
Table: Patients

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| patient_id   | int     |
| patient_name | varchar |
| conditions   | varchar |
+--------------+---------+

patient_id는 이 테이블에서 기본 키(고유 값을 가진 열)입니다.
'conditions'는 공백으로 구분된 0개 이상의 코드가 포함되어 있습니다.
이 테이블은 병원에 있는 환자에 대한 정보를 포함하고 있습니다.

 

문제

Type I Diabetes는 항상 DIAB1 접두사로 시작합니다. Type I Diabetes가 있는 환자들의 patient_id, patient_name, conditions를 찾는 해결책을 작성하십시오.
결과 테이블은 임의의 순서로 반환하십시오.

결과 형식은 아래 예시와 같습니다.

Example 1:

Input: 
Patients table:
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 1          | Daniel       | YFEV COUGH   |
| 2          | Alice        |              |
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 |
| 5          | Alain        | DIAB201      |
+------------+--------------+--------------+
Output: 
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 | 
+------------+--------------+--------------+

설명 : Bob과 George는 모두 DIAB1로 시작하는 상태를 가지고 있습니다.

 

✏️ 풀이

import pandas as pd

def find_patients(patients: pd.DataFrame) -> pd.DataFrame:
    pattern = r'DIAB1'

    return patients[patients['conditions'].str.contains(pattern, regex=True)]

정규식은 아직도 어렵다~.~