BI & Visualization/Python
Pandas | LeetCode 1757. 연산자를 사용하여 조건 만족하는 행 추출하기
올리브한입
2025. 5. 23. 06:05
반응형
Table: Products
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| low_fats | enum |
| recyclable | enum |
+-------------+---------+
product_id is the primary key (column with unique values) for this table.
low_fats is an ENUM (category) of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
recyclable is an ENUM (category) of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.
Write a solution to find the ids of products that are both low fat and recyclable.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Products table:
+-------------+----------+------------+
| product_id | low_fats | recyclable |
+-------------+----------+------------+
| 0 | Y | N |
| 1 | Y | Y |
| 2 | N | Y |
| 3 | Y | Y |
| 4 | N | N |
+-------------+----------+------------+
Output:
+-------------+
| product_id |
+-------------+
| 1 |
| 3 |
+-------------+
Explanation: Only products 1 and 3 are both low fat and recyclable.
import pandas as pd
def find_products(products: pd.DataFrame) -> pd.DataFrame:
#low_fats = products['low_fats'] == 'Y'
#recyclable = products['recyclable'] == 'Y'
#low_f_n_rcy = products[low_fats & recyclable]
#return low_f_n_rcy[['product_id']]
return products[
(products['low_fats'] == 'Y') & (products['recyclable'] == 'Y')
][['product_id']]
- (products['low_fats'] == 'Y'): 저지방 제품 필터링
- (products['recyclable'] == 'Y'): 재활용 가능 제품 필터링
- & 연산자를 통해 두 조건을 모두 만족하는 행만 추출
- 마지막에 [['product_id']]로 원하는 열만 선택
반응형