[Study]/[Pandas]

[LeetCode - Pandas] (Easy) 2887. Fill Missing Data

잰잰' 2025. 3. 28. 15:24
DataFrame products
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| name        | object |
| quantity    | int    |
| price       | int    |
+-------------+--------+

수량 열에서 누락된 값을 0으로 채우는 해결 방법을 작성하세요. 결과 형식은 아래 예시와 같습니다.

 

Example 1:
Input:+-----------------+----------+-------+
| name            | quantity | price |
+-----------------+----------+-------+
| Wristwatch      | None     | 135   |
| WirelessEarbuds | None     | 821   |
| GolfClubs       | 779      | 9319  |
| Printer         | 849      | 3051  |
+-----------------+----------+-------+
Output:
+-----------------+----------+-------+
| name            | quantity | price |
+-----------------+----------+-------+
| Wristwatch      | 0        | 135   |
| WirelessEarbuds | 0        | 821   |
| GolfClubs       | 779      | 9319  |
| Printer         | 849      | 3051  |
+-----------------+----------+-------+

설명:
Wristwatch(손목시계)와 WirelessEarbuds(무선 이어폰)의 수량은 0으로 채워졌습니다.

 

풀이

import pandas as pd

def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
    products.fillna(value=0, inplace=True)

    return products

 

개념 정리

fillna : 데이터 프레임에서 결측값을 원하는 값으로 변경하는 메서드

value : 결측값을 대체할 값

inplace : 원본을 변경할지 여부

method : 결측값을 변경할 방식

               bfill = 결측값을 바로 아래 값과 동일하게 변경 / fill - 바로 윗 값과 동일하게 변경

axis : 메서드를 적용할 레이블 0 = index / 1 = column

limit : 결측값을 변경할 횟수. 위에서부터 지정된 수만큼 변경