반응형
Table: Tweets
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
content consists of alphanumeric characters, '!', or ' ' and no other special characters.
This table contains all the tweets in a social media app.
Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Tweets table:
+----------+-----------------------------------+
| tweet_id | content |
+----------+-----------------------------------+
| 1 | Let us Code |
| 2 | More than fifteen chars are here! |
+----------+-----------------------------------+
Output:
+----------+
| tweet_id |
+----------+
| 2 |
+----------+
Explanation:
Tweet 1 has length = 11. It is a valid tweet.
Tweet 2 has length = 33. It is an invalid tweet.
해결 방법
- str.len()을 이용해 문자열 길이 계산
- 길이가 15 초과인 행만 필터링
- tweet_id만 선택
import pandas as pd
def invalid_tweets(tweets: pd.DataFrame) -> pd.DataFrame:
tweets['tw_len'] = tweets['content'].str.len()
result = tweets[tweets['tw_len'] > 15][['tweet_id']]
return result
- str.len()은 Pandas에서 문자열 관련 처리를 할 때 아주 자주 사용하는 함수입니다.
- .loc 없이도 조건 필터링이 가능하므로 코드가 간결합니다.
- 출력에서 [['tweet_id']]처럼 이중 대괄호를 쓰는 건 DataFrame 형태로 반환하기 위함입니다. ['tweet_id']는 Series 반환입니다.
반응형
'BI & Visualization > Python' 카테고리의 다른 글
Pandas | LeetCode 1148. 자신이 쓴 글을 본 작가 찾기 (0) | 2025.05.25 |
---|---|
Pandas | LeetCode 183. 주문하지 않은 고객 찾기 (2) | 2025.05.24 |
Pandas | LeetCode 1757. 연산자를 사용하여 조건 만족하는 행 추출하기 (3) | 2025.05.23 |
Pandas | LeetCode 595. World 테이블에서 큰 나라 찾기 (2) | 2025.05.22 |