Table: Products
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| product_id | int |
| product_name | varchar |
| product_category | varchar |
+------------------+---------+
product_id는 이 테이블의 기본 키(고유 값이 있는 열)입니다.
이 테이블은 회사의 제품에 대한 데이터를 포함하고 있습니다.
Table: Orders
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| order_date | date |
| unit | int |
+---------------+---------+
이 테이블에는 중복된 행이 있을 수 있습니다.
product_id는 Products 테이블에 대한 외래 키(참조 열)입니다.
unit은 order_date에 주문된 제품의 수입니다.
문제
2020년 2월에 최소 100개의 단위가 주문된 제품의 이름과 해당 금액을 가져오는 솔루션을 작성하세요.
결과 테이블은 어떤 순서로든 반환하십시오.
결과 형식은 다음 예와 같습니다.
Example 1:
Input:
Products table:
+-------------+-----------------------+------------------+
| product_id | product_name | product_category |
+-------------+-----------------------+------------------+
| 1 | Leetcode Solutions | Book |
| 2 | Jewels of Stringology | Book |
| 3 | HP | Laptop |
| 4 | Lenovo | Laptop |
| 5 | Leetcode Kit | T-shirt |
+-------------+-----------------------+------------------+
Orders table:
+--------------+--------------+----------+
| product_id | order_date | unit |
+--------------+--------------+----------+
| 1 | 2020-02-05 | 60 |
| 1 | 2020-02-10 | 70 |
| 2 | 2020-01-18 | 30 |
| 2 | 2020-02-11 | 80 |
| 3 | 2020-02-17 | 2 |
| 3 | 2020-02-24 | 3 |
| 4 | 2020-03-01 | 20 |
| 4 | 2020-03-04 | 30 |
| 4 | 2020-03-04 | 60 |
| 5 | 2020-02-25 | 50 |
| 5 | 2020-02-27 | 50 |
| 5 | 2020-03-01 | 50 |
+--------------+--------------+----------+
Output:
+--------------------+---------+
| product_name | unit |
+--------------------+---------+
| Leetcode Solutions | 130 |
| Leetcode Kit | 100 |
+--------------------+---------+
설명 :
product_id = 1인 제품은 2월에 총 (60 + 70) = 130개가 주문되었습니다.
product_id = 2인 제품은 2월에 총 80개가 주문되었습니다.
product_id = 3인 제품은 2월에 총 (2 + 3) = 5개가 주문되었습니다.
product_id = 4인 제품은 2020년 2월에 주문되지 않았습니다.
product_id = 5인 제품은 2월에 총 (50 + 50) = 100개가 주문되었습니다.
✏️ 풀이
import pandas as pd
def list_products(products: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
df = orders[(orders['order_date'].dt.year == 2020) & (orders['order_date'].dt.month == 2)]
df = df.groupby('product_id')['unit'].sum().reset_index(name='unit')
result = pd.merge(df, products, how='inner', on='product_id')
return result[result['unit'] >= 100][['product_name', 'unit']]
1. 2020년 2월 데이터 필터
2. 각 product_id별로 unit의 sum값 구하기
3. sum값이 100 이상인 것만 조회
'[코딩테스트] > [Pandas]' 카테고리의 다른 글
[LeetCode - Pandas] (Easy) 1251. Average Selling Price (0) | 2025.04.19 |
---|---|
[LeetCode - Pandas] (Easy) 1280. Students and Examinations (0) | 2025.04.18 |
[LeetCode - Pandas] (Easy) 1378. Replace Employee ID With The Unique Identifier (0) | 2025.04.17 |
[LeetCode - Pandas] (Easy) 1407. Top Travellers (4) | 2025.04.17 |
[LeetCode - Pandas] (Easy) 1484. Group Sold Products By The Date (0) | 2025.04.16 |