[Study]/[Pandas]

[LeetCode - Pandas] (Easy) 2883. Drop Missing Data

잰잰' 2025. 3. 31. 12:21
DataFrame students
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| student_id  | int    |
| name        | object |
| age         | int    |
+-------------+--------+

"이름" 열에 누락된 값이 있는 일부 행이 있습니다.

누락된 값이 있는 행을 제거하는 솔루션을 작성하세요.

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

Example 1:
Input:
+------------+---------+-----+
| student_id | name    | age |
+------------+---------+-----+
| 32         | Piper   | 5   |
| 217        | None    | 19  |
| 779        | Georgia | 20  |
| 849        | Willow  | 14  |
+------------+---------+-----+
Output:
+------------+---------+-----+
| student_id | name    | age |
+------------+---------+-----+
| 32         | Piper   | 5   |
| 779        | Georgia | 20  | 
| 849        | Willow  | 14  | 
+------------+---------+-----+

설명: 학생 ID 217은 이름 열에 빈 값이 있으므로 해당 행은 제거됩니다.

 

✏️ 풀이

import pandas as pd

def dropMissingData(students: pd.DataFrame) -> pd.DataFrame:
    return students.dropna(subset=['name'])

 

📚 개념정리

dropna() ? 데이터프레임 내의 결측값을 제거하는 메서트

df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

axis : 0 = index / 1 = columns 결측치를 제거할 레이블

how : any = 존재하면 제거 / all = 모두 결측치면 제거

thresh : 결측값이 아닌 값이 설정한 값 미만일 경우에만 적용 (5라고 하면 5개 미만일 경우에만)

subset : 결측값 제거를 할 레이블 지정

inplace : 원본 변경 여부