BI & Visualization/Python
Pandas | LeetCode 183. 주문하지 않은 고객 찾기
올리브한입
2025. 5. 24. 07:37
반응형

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
반응형