본문 바로가기
Python/Pandas LeetCode 코딩테스트

584. Find Customer Referee

by Nanki 2025. 3. 13.

Table: Customer

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| referee_id  | int     |
+-------------+---------+


In SQL, id is the primary key column for this table.
Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them.
 

Find the names of the customer that are not referred by the customer with id = 2.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Customer table:
+----+------+------------+
| id | name | referee_id |
+----+------+------------+
| 1  | Will | null       |
| 2  | Jane | null       |
| 3  | Alex | 2          |
| 4  | Bill | null       |
| 5  | Zack | 1          |
| 6  | Mark | 2          |
+----+------+------------+
Output: 
+------+
| name |
+------+
| Will |
| Jane |
| Bill |
| Zack |

 

 

id=2가 아닌 referred 고객을 찾아서 어떤 정렬이건 리턴해라.


1) referee_id가 2가 아니면 되기에 loc[]를 사용해준다. 
2) 단, 결측이 섞여있는 경우 2가 아닌 다른 값들만 가져와달라해도 결측값 또한 제거한 후 가져온다.
> 이는 NaN이 Boolean Indexing에서 NaN 비교시 False로 연산되기 때문.
> 결측을 다른 값으로 바꿔주고 loc[]을 활용해 주도록하자.
3) 2) 번의 또 다른 방법은 isna() 를 조건으로 추가해줄수도있다.

import pandas as pd

def find_customer_referee(customer: pd.DataFrame) -> pd.DataFrame:
    customer['referee_id'].fillna(1, inplace = True)
    print(customer)
    return customer.loc[customer['referee_id'] != 2, ['name']]




또 다른 방법
단 여기서 주의해야 할점이 또 있다.

1. isna() 자체가 True, False를 반환한다. 즉 isna() == True를 붙일 필요가 없다. 
2. 아래 조건에서 != 연산자가 | 연산자보다 우선으로 처리가 된다. 따라서 뒤의 isna()조건이 or 연산자로 식별되지도 못하고 NaN은 != 연산자로 인해 False로 처리되고, NaN이 있는 값들은 인덱싱에서 제외된다.
> 따라서 반드시 조건문에 괄호 () 를 쳐줘야 한다.

import pandas as pd

def find_customer_referee(customer: pd.DataFrame) -> pd.DataFrame:
    return customer.loc[(customer['referee_id'] != 2) | (customer['referee_id'].isna()), ['name']]


    
오늘 알게 된 것

isna()

!= 와 |의 연산 순서 

반응형

'Python > Pandas LeetCode 코딩테스트' 카테고리의 다른 글

197. Rising Temperature  (0) 2025.03.13
181. Employees Earning More Than Their Managers  (0) 2025.03.12
176. Second Highest Salary  (0) 2025.03.12