반응형
Table: Customers
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the ID and name of a customer.
Table: Orders
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| customerId | int |
+-------------+------+
id is the primary key (column with unique values) for this table.
customerId is a foreign key (reference columns) of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.
Write a solution to find all customers who never order anything.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Customers table:
+----+-------+
| id | name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
Output:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
import pandas as pd
def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
customer_w_orders = orders['customerId']
orderornot = customers['id'].isin(customer_w_orders)
never_ordered = customers[~orderornot]
result = never_ordered[['name']].rename(columns={'name': 'Customers'})
return result
- isin()은 포함된 값을 찾을 때 사용
- ~isin()은 포함되지 않은 값을 찾을 때 사용
- SQL로 치면 NOT IN (...) 조건과 같습니다
밑은 예시입니다.
customers['id']
# 결과: [1, 2, 3, 4]
ordered_customer_ids = [3, 1]
customers['id'].isin(ordered_customer_ids)
# 결과: [True, False, True, False]
~customers['id'].isin(ordered_customer_ids)는:
[False, True, False, True]
= 주문한 적 없는 고객만 True
반응형
'BI & Visualization > Python' 카테고리의 다른 글
Pandas | LeetCode 1683. 15자를 초과한 트윗 찾기 (1) | 2025.05.26 |
---|---|
Pandas | LeetCode 1148. 자신이 쓴 글을 본 작가 찾기 (0) | 2025.05.25 |
Pandas | LeetCode 1757. 연산자를 사용하여 조건 만족하는 행 추출하기 (3) | 2025.05.23 |
Pandas | LeetCode 595. World 테이블에서 큰 나라 찾기 (2) | 2025.05.22 |