반응형
Table: Views
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| article_id | int |
| author_id | int |
| viewer_id | int |
| view_date | date |
+---------------+---------+
There is no primary key (column with unique values) for this table, the table may have duplicate rows.
Each row of this table indicates that some viewer viewed an article (written by some author) on some date.
Note that equal author_id and viewer_id indicate the same person.
Write a solution to find all the authors that viewed at least one of their own articles.
Return the result table sorted by id in ascending order.
The result format is in the following example.
Example 1:
Input:
Views table:
+------------+-----------+-----------+------------+
| article_id | author_id | viewer_id | view_date |
+------------+-----------+-----------+------------+
| 1 | 3 | 5 | 2019-08-01 |
| 1 | 3 | 6 | 2019-08-02 |
| 2 | 7 | 7 | 2019-08-01 |
| 2 | 7 | 6 | 2019-08-02 |
| 4 | 7 | 1 | 2019-07-22 |
| 3 | 4 | 4 | 2019-07-21 |
| 3 | 4 | 4 | 2019-07-21 |
+------------+-----------+-----------+------------+
Output:
+------+
| id |
+------+
| 4 |
| 7 |
+------+
def article_views(views: pd.DataFrame) -> pd.DataFrame:
# 자신이 본 글만 필터링
result = views[views['author_id'] == views['viewer_id']]
# 중복 제거된 작가 id 추출
unique_result = result['author_id'].unique()
# DataFrame으로 변환 후 정렬
unique_result_df = pd.DataFrame({'id': unique_result})
return unique_result_df.sort_values(by='id').reset_index(drop=True)
- views['author_id'] == views['viewer_id']는 두 컬럼이 같은지 비교합니다.
- 결과는 True/False를 반환하는 Boolean Series이고,
- 이 조건을 이용해 views DataFrame을 필터링하면 자기 글을 본 행만 남습니다.
- self_views['author_id']는 자신이 본 글의 작가 ID들만 담고 있는 Series입니다.
- .unique()는 중복을 제거해 고유한 값만 반환합니다.
- 이 결과는 NumPy 배열 형태입니다.
- pd.DataFrame({'id': unique_authors})로 id라는 컬럼명을 가진 DataFrame을 만듭니다.
- .sort_values(by='id')는 오름차순으로 정렬합니다.
- .reset_index(drop=True)는 정렬 후 인덱스를 다시 부여해 깔끔하게 만듭니다.
반응형
'BI & Visualization > Python' 카테고리의 다른 글
Pandas | LeetCode 1683. 15자를 초과한 트윗 찾기 (1) | 2025.05.26 |
---|---|
Pandas | LeetCode 183. 주문하지 않은 고객 찾기 (2) | 2025.05.24 |
Pandas | LeetCode 1757. 연산자를 사용하여 조건 만족하는 행 추출하기 (3) | 2025.05.23 |
Pandas | LeetCode 595. World 테이블에서 큰 나라 찾기 (2) | 2025.05.22 |