leetcode : 1729. Find Followers Count
다이어그램
erDiagram
FOLLOWS {
int user_id PK
int follower_id PK
}
각 유져별로 팔로워 수를 구한다
문제 풀이
MySQL
SELECT USER_ID, COUNT(*) AS FOLLOWERS_COUNT
FROM FOLLOWERS
GROUP BY USER_ID
ORDER BY USER_ID
- 단순 GROUP BY + COUNT 문제
MySQL 2
SELECT USER_ID, COUNT(DISTINCT FOLLOWER_ID) AS FOLLOWERS_COUNT
FROM FOLLOWERS
GROUP BY USER_ID
- 중복 팔로잉이 존재할거같아서 COUNT DISTINCT를 사용했다.
Pandas 1
import pandas as pd
def count_followers(followers: pd.DataFrame) -> pd.DataFrame:
grouped = followers.groupby('user_id').agg(
followers_count = ('follower_id','size')
).reset_index()
return grouped
- 단순 group by + count문제
Pandas 2
def count_followers(followers: pd.DataFrame) -> pd.DataFrame:
grouped = followers.groupby(by=['user_id']).agg(
followers_count = ('follower_id','nunique')
).reset_index()
return grouped
- 중복 id가 발생하는걸 고려해서 nunique를 썼는데 정답은 똑같다.
코멘트
- 쉬운문제
'Data Analysis > SQL Pandas' 카테고리의 다른 글
leetcode : 1890. The Latest Login in 2020 (0) | 2025.02.11 |
---|---|
leetcode : 1873. Calculate Special Bonus (0) | 2025.02.10 |
leetcode : 1789. Primary Department for Each Employee (0) | 2025.02.09 |
leetcode : 1693. Daily Leads and Partners (0) | 2025.02.06 |
leetcode : 1683. Invalid Tweets (0) | 2025.02.06 |
leetcode : 1667. Fix Names in a Table (0) | 2025.02.06 |
leetcode : 1661. Average Time of Process per Machine (0) | 2025.02.05 |
댓글