Pandas: 다중 집계와 함께 groupby를 사용하는 방법
다음 기본 구문을 사용하여 Pandas에서 여러 집계와 함께 groupby를 사용할 수 있습니다.
df. groupby (' team '). agg ( mean_points=(' points ', np. mean ), sum_points=(' points ', np. sum ), std_points=(' points ', np. std ))
이 특정 공식은 DataFrame의 행을 team 이라는 변수로 그룹화한 다음 points 라는 변수에 대한 여러 요약 통계를 계산합니다.
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: Pandas에서 다중 집계와 함께 Groupby 사용
다양한 농구 선수에 대한 정보가 포함된 다음과 같은 pandas DataFrame이 있다고 가정합니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Mavs', 'Mavs', 'Heat', 'Heat', 'Heat'], ' points ': [18, 22, 19, 14, 14, 11], ' assists ': [5, 7, 7, 9, 12, 9]}) #view DataFrame print (df) team points assists 0 Mavs 18 5 1 Mavs 22 7 2 Mavs 19 7 3 Heat 14 9 4 Heat 14 12 5 Heat 11 9
다음 구문을 사용하여 DataFrame의 행을 팀별 로 그룹화한 다음 각 팀 포인트 의 평균, 합계 및 표준 편차를 계산할 수 있습니다.
import numpy as np #group by team and calculate mean, sum, and standard deviation of points df. groupby (' team '). agg ( mean_points=(' points ', np. mean ), sum_points=(' points ', np. sum ), std_points=(' points ', np. std )) mean_points sum_points std_points team Heat 13.000000 39 1.732051 Mavs 19.666667 59 2.081666
결과에는 각 팀 의 점수 변수의 평균, 합계 및 표준 편차가 표시됩니다.
유사한 구문을 사용하여 그룹화를 수행하고 원하는 만큼 집계를 계산할 수 있습니다.
추가 리소스
다음 튜토리얼에서는 다른 일반적인 Panda 작업을 수행하는 방법을 설명합니다.
Pandas GroupBy를 사용하여 고유한 값을 계산하는 방법
Pandas Groupby에 기능을 적용하는 방법
Pandas GroupBy에서 막대 그래프를 만드는 방법