[Python] 03. Grouping

hhyun·2024년 6월 18일

[Python]

목록 보기
3/11

📖 Grouping

🌟 Grouping

  • 그룹을 지어서 특정 관점을 가지고 데이터를 추출
메서드설명
groupby데이터를 그룹화하여 연산을 수행
size()null을 포함해 출력
counts()null을 포함하지 않고 출력
sort_index()인덱스를 기준으로 레이블을 정렬
value.counts()고유한 행의 갯수를 반환
value_counts(dropna = False)결측치가 포함된 행을 계산
to_frame()데이터프레임으로 변환
as_index=False그룹 연산의 결과를 인덱스가 아닌 정규 열로 반환
agg()여러개의 함수를 동시에 적용
mean평균
var분산
max최대
min최소
unstack()행을 언피벗하여 하위 열로 변환하는 메서드
fillnaDataFrame에서 결측값을 원하는 값으로 변경

🌟 상위 5개를 출력

💭 Q44. 데이터를 로드하고 상위 5개 컬럼을 출력

import pandas as pd
DriveUrl = (`링크`)
df= pd.read_csv(DriveUrl)
Ans =df.head(5)
Ans

💭 Q45. 데이터의 각 host_name의 빈도수를 구하고 host_name으로 정렬 후 상위 5개를 출력

Ans = df.groupby('host_name').size().sort_index()
#or
Ans = df.host_name.value_counts().sort_index()
Ans.head()

💭 Q46. 데이터의 각 host_name의 빈도수를 구하고 빈도수로 정렬 후 상위 5개를 출력

  • to_frame() : 데이터프레임으로 변환
Ans = df.groupby('host_name').size().\
                to_frame().rename(columns={0:'counts'}).\
                sort_values('counts',ascending=False)
Ans.head(5)

🌟 칼럼 하나로 groupby

💭 Q47. neighbourhood_group의 값에 따른 neighbourhood컬럼 값의 갯수 출력

Ans = df.groupby(['neighbourhood_group','neighbourhood'], as_index=False).size()
Ans.head()

💭 Q48. neighbourhood_group의 값에 따른 neighbourhood컬럼 값 중 neighbourhood_group그룹의 최댓값들을 출력

Ans= df.groupby(['neighbourhood_group','neighbourhood'], as_index=False).size()\
                  .groupby(['neighbourhood_group'], as_index=False).max()
Ans

🌟 price값의 평균, 분산, 최대, 최소 값 출력

💭 Q49. neighbourhood_group 값에 따른 price값의 평균, 분산, 최대, 최소 값 출력

Ans = df.groupby('neighbourhood_group')['price'].agg(['mean','var','max','min'])
Ans

💭 Q50. 데이터중 neighbourhood_group 값이 Queens값을 가지는 데이터들 중 neighbourhood 그룹별로 price값의 평균, 분산, 최대, 최소 값 출력

Ans = df[df.neighbourhood_group=='Queens'].groupby(['neighbourhood']).price.agg(['mean','var','max','min'])
Ans

🌟 두 컬럼의 값에 인한 groupby

💭 Q51. neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 구하기

  • groupby 의 안쪽 순서에 따라 데이터 정렬이 달라진다.
# Ans = df.groupby(['neighbourhood','neighbourhood_group']).price.mean()
Ans = df.groupby(['neighbourhood','neighbourhood_group'])['price'].mean()
Ans

💭 Q52. neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 계층적 indexing 없이 구하기

# Ans = df.groupby(['neighbourhood','neighbourhood_group']).price.mean().unstack()
Ans = df.groupby(['neighbourhood_group', 'neighbourhood']).price.mean().unstack()
Ans

💭 Q53. neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 계층적 indexing 없이 구하고 nan 값은 -999값으로 채우기

Ans = df.groupby(['neighbourhood_group', 'neighbourhood']).price.mean().
	unstack().fillna(-999)
Ans

🌟 데이터 중 neighbourhood_group 값에 따른

💭 Q54. 데이터중 neighbourhood_group 값이 Queens값을 가지는 데이터들 중 neighbourhood 그룹별로 price값의 평균, 분산, 최대, 최소값을 구하기

Ans = df[df.neighbourhood_group=='Queens'].groupby(['neighbourhood']).price.agg(['mean','var','max','min'])
Ans

💭 Q55. 데이터 중 neighbourhood_group 값에 따른 room_type 컬럼의 숫자를 구하고 neighbourhood_group 값을 기준으로 각 값의 비율을 구하기

  • reshape(변경할 배열, 차원) : 배열과 차원을 변형해주는 함수
Ans = df[['neighbourhood_group','room_type']].groupby(['neighbourhood_group','room_type']).size().unstack()
Ans.loc[:,:] = (Ans.values /Ans.sum(axis=1).values.reshape(-1,1))
Ans

0개의 댓글