Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas로 관측값 개수 세기 – groupby()와 count() 완벽 가이드

Pandas에서 데이터프레임의 관측값(행) 개수를 세려면 먼저 groupby() 함수로 데이터를 그룹화한 뒤, 그 결과에 count()를 적용하면 됩니다. 이 글에서는 실제 예제를 통해 단계별로 살펴보겠습니다.

1단계: 라이브러리 임포트

가장 먼저 필요한 라이브러리를 가져옵니다.

import pandas as pd

2단계: 데이터프레임 생성

예제로 사용할 데이터프레임을 만들어 보겠습니다. 제품명, 제품 카테고리, 수량 정보를 담은 간단한 데이터입니다.

dataFrame = pd.DataFrame({
    'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],
    'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
    'Quantity': [10, 50, 10, 20, 25, 50]
})

3단계: 중복 값이 있는 열로 그룹화

카테고리별로 개수를 세기 위해 중복 값이 존재하는 'Product Category' 열을 기준으로 그룹화합니다.

group = dataFrame.groupby("Product Category")

4단계: 관측값 개수 구하기

그룹 객체에 count()를 호출하면 각 카테고리별 관측값 개수를 확인할 수 있습니다.

group.count()

전체 예제 코드

지금까지의 과정을 하나의 코드로 정리하면 다음과 같습니다.

import pandas as pd

# 데이터프레임 생성
dataFrame = pd.DataFrame({
    'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],
    'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
    'Quantity': [10, 50, 10, 20, 25, 50]
})

# 데이터프레임 출력
print("Dataframe...\n", dataFrame)

# 관측값 개수 세기
group = dataFrame.groupby("Product Category")

print("\nResultant DataFrame...\n", group.count())

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Dataframe...
    Product Category   Product Name   Quantity
0          Computer        Keyboard         10
1      Mobile Phone         Charger         50
2       Electronics        SmartTV         10
3       Electronics         Camera         20
4          Computer    Graphic Card         25
5      Mobile Phone       Earphone         50

Resultant DataFrame...
                    Product Name   Quantity
Product Category
Computer                     2           2
Electronics                  2           2
Mobile Phone                 2           2

결과 해석

'Computer', 'Electronics', 'Mobile Phone' 각 카테고리에 제품이 2개씩 속해 있으므로, 모든 그룹의 관측값이 2로 집계되었습니다. 참고로 count()는 열별로 결측값(NaN)을 제외한 유효한 값의 개수를 반환하기 때문에, 특정 열에 빈 값이 있다면 열마다 집계 결과가 달라질 수 있습니다.