Leetcode_30 Days of Pandas
문제 출처
https://leetcode.com/studyplan/30-days-of-pandas/
1. 문제
"Patients With a Condition" / 환자 상태
Table :Patients
Coulumn Name | Type |
patient_id | int |
patient_name | varchar |
conditions | varchar |
Write a solution to find the patient_id, patient_name, and conditions of the patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1 prefix.
Return the result table in any order.
input |
► |
output |
||||
patient_id | patient_name | conditions | user_id | patient_name | conditions | |
1 | Daniel | YFEV COUGH | 3 | Bob | DIAB100 MYOP | |
2 | Alice | 4 | George | ACNE DIAB100 | ||
3 | Bob | DIAB100 MYOP | ||||
4 | George | ACNE DIAB100 | ||||
5 | Alain | DIAB201 |
CheckPoint
1. 당뇨병(Diabetes)을 가진 환자만 출력
2. 환자 컨디션은 DIAB1으로 시작
2. 문제 풀이
1차시. 오답
1. Patients테이블에서 conditions에서 "DIAB1"있는 데이터 match로 추출
2. user id로 오름차순으로 정렬 후 출력
오답노트
1. 결측치 예외처리
2. 정답은 맞음
import pandas as pd
def find_patients(patients: pd.DataFrame) -> pd.DataFrame:
patients['conditions'] = patients['conditions'].str.contains('DIAB1')
result_df = patients.sort_values(by='patient_id', ascending=True)
return result_df
2차시. 오답
1. 결측치 dropna() 추가
오답노트
1. Alain / DIAB201도 DIAB로 시작하지만, 예외 > 왜??
2. Solution 확인
import pandas as pd
def find_patients(patients: pd.DataFrame) -> pd.DataFrame:
patients['conditions'] = patients['conditions'].str.contains('DIAB1')
patients = patients.dropna()
result_df = patients.sort_values(by='patient_id', ascending=True)
return result_df
3차시. 솔루션 확인, 정답
오답노트
1. query
- query method로 조건 필터링
2. conditions.str.startswith(r'DIAB1')
- conditions 열에서 각 문자열이 'DIAB1'로 시작하는지를 확인
- startswith 함수는 문자열이 주어진 접두사(DIAB1)로 시작하는지 여부를 확인하는 데 사용
3. conditions.str.contains(r' DIAB1')
- conditions 열에서 각 문자열에 ' DIAB1'이라는 부분 문자열이 포함되어 있는지를 확인, contains 함수는 문자열 내에 특정 부분 문자열이 존재하는지 여부를 확인하는 데 사용
- 여기서 ' DIAB1' 앞의 공백은 'DIAB1'이 단어의 시작 부분이 아니라 중간에 나타날 경우를 처리하기 위해 포함
import pandas as pd
def find_patients(patients: pd.DataFrame) -> pd.DataFrame:
return patients.query("conditions.str.startswith(r'DIAB1') or
conditions.str.contains(r' DIAB1')")
'Python > LeetCode' 카테고리의 다른 글
[LeetCode] String Methods 1517. Find Users With Valid E-Mails (0) | 2024.01.03 |
---|---|
[LeetCode] String Methods 1667. Fix Names in a Table (0) | 2024.01.03 |