파이썬 그룹별 최빈 단어 추출
조회수 890회
그룹별로 가장 빈도수가 높은 단어 3개를 추출하고 싶습니다. 예를 들면 자료가 위와 같을 때 아래와 같은 output을 산출하고 싶습니다.
A 감 3 바나나 2 사과 1 딸기 1
B 광어 2 우럭 1
Counter(most_common)와 group-by를 함께 쓸 수 있을까요?
2 답변
-
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> import pandas as pd >>> df = pd.DataFrame({"cat":list("AAABB"), "cont":[ ["사과", "바나나", "감"], ["딸기","바나나","감"],["감"], ["광어", "우럭"],["광어"]]}) >>> df cat cont 0 A [사과, 바나나, 감] 1 A [딸기, 바나나, 감] 2 A [감] 3 B [광어, 우럭] 4 B [광어] >>> df.groupby("cat").cont.sum() cat A [사과, 바나나, 감, 딸기, 바나나, 감, 감] B [광어, 우럭, 광어] Name: cont, dtype: object >>> grouped = df.groupby("cat").cont.sum() >>> grouped cat A [사과, 바나나, 감, 딸기, 바나나, 감, 감] B [광어, 우럭, 광어] Name: cont, dtype: object >>> df2 = grouped.to_frame() >>> df2 cont cat A [사과, 바나나, 감, 딸기, 바나나, 감, 감] B [광어, 우럭, 광어] >>> from collections import Counter >>> for c, l in df2.itertuples(): print(Counter(l)) Counter({'감': 3, '바나나': 2, '사과': 1, '딸기': 1}) Counter({'광어': 2, '우럭': 1}) >>> for c, l in df2.itertuples(): print(c, Counter(l)) A Counter({'감': 3, '바나나': 2, '사과': 1, '딸기': 1}) B Counter({'광어': 2, '우럭': 1}) >>>
-
content 만 필요하기 때문에 groupby 로 묶는 것 보다 같은 항목을 다 append 하여 Counter 를 적용하는 것이 간단합니다.
data = [{'category':'A', 'content': ['사과', '바나나', '감']}, {'category':'A', 'content': ['딸기', '바나나', '감']}, {'category':'A', 'content': ['감']}, {'category':'B', 'content': ['광어', '우럭']}, {'category':'B', 'content': ['광어']}] from collections import defaultdict, Counter result = defaultdict(list) for d in data: result[d['category']] += d['content'] {k: Counter(g).most_common(3) for k, g in result.items()} {'A': [('감', 3), ('바나나', 2), ('사과', 1)], 'B': [('광어', 2), ('우럭', 1)]}
댓글 입력