[실습] Python : 03. Grouping

yeppi1802·2024년 6월 22일

개념정리

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

import pandas as pd
DriveUrl = '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()
  # groupby(column) : 컬럼으로 그룹화 
  # size() : null 포함 카운트
  # sort_index() : host_name 컬럼이 인덱스로 됨, 오름차순 정렬
# or

Ans = df.host_name.value_counts().sort_index()
  # counts() : null 포함하지 않고 카운트 
  # value_counts() : 컬럼이 가지고 있는 유일 값 추출, 갯수 많은 순서대로 내림차순 
Ans.head()

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

# df.host_name.value_counts().to_frame().head()
# OR 

Ans = df.groupby('host_name').size().\      # \ : 엔터 표시
                to_frame().rename(columns={0:'counts'}).\
                sort_values('counts',ascending=False) 
# to_frame : 데이터 프레임으로 변경
# rename(columns={0:'counts'}) : 0을 counts로 컬럼명 변경
# sort_values('counts',ascending=False) : counts 기준으로 내림차순
Ans.head(5)

Q47. neighbourhood_group의 값에 따른 neighbourhood컬럼 값의 갯수를 구하여라

Ans = df.groupby(['neighbourhood_group','neighbourhood'], as_index=False).size()
# group by에서 ['neighbourhood_group','neighbourhood'] 대괄호로 두가지 기준으로 그룹화 
# as_index=False : 인덱스로 설정되는 것이 아닌, 컬럼으로 시각화 
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()
# max() : 최댓값 
# groupby함수 한번더 사용하여 대분류그룹의 최대값 구함 
Ans

Q49. neighbourhood_group 값에 따른 price값의 평균, 분산, 최대, 최소 값을 구하여라

Ans = df.groupby('neighbourhood_group')['price'].agg(['mean','var','max','min'])
# 'neighbourhood_group'으로  묶고, 
# 'price'의 데이터를 ['mean','var','max','min']와 같은 값을 구할것이다
# agg() : 어떤 사칙연산을 할것인지 선언, 여러 사칙연산 할 경우 대괄호로 묶어줌 
Ans

Q50. neighbourhood_group 값에 따른 reviews_per_month 평균, 분산, 최대, 최소 값을 구하여라

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

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

Ans = df.groupby(['neighbourhood','neighbourhood_group']).price.mean()
# .price == ['price']
# 하나의 사칙연산 사용시 agg 사용하지 않고 .mean()과 같이 표현 가능 
Ans

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

# 계층적 indexing = 51번 결과 같이 계층을 이룬 시각화
# Ans = df.groupby([**'neighbourhood','neighbourhood_group'**]).price.mean().unstack()
                   # 컬럼 순서 다르면 결과 바뀜 
Ans = df.groupby(['neighbourhood_group', 'neighbourhood']).price.mean().unstack()
# unstack() : 
Ans

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

Ans = df.groupby(['neighbourhood','neighbourhood_group'])\
								.price.mean().unstack().fillna(-999)
# fillna(-999) : 빈값이 있으면 -999로 넣어주겠다. 
Ans 

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

Ans = df[df.neighbourhood_group=='Queens']\
					.groupby(['neighbourhood']).price.agg(['mean','var','max','min'])
# neighbourhood_group가 'Queens'인 데이터 중
# neighbourhood 기준 그룹별
# price값의 평균, 분산, 최대, 최소값
Ans

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

Ans = df[['neighbourhood_group','room_type']]\
      .groupby(['neighbourhood_group','room_type']).size().unstack()
# 'neighbourhood_group','room_type' 컬럼 추출
# 'neighbourhood_group','room_type' 그룹화
# .size().unstack() : 숫자 구함 
Ans.sum(axis=1)
# 각 행에 대해 sum 값 
# axis=1 : 컬럼값을 기준으로 1
Ans.sum(axis=1).values.reshape(-1,1)
# values : 값 추출 
# reshape() : 데이터의 행과 열의 갯수 변경
# -1,1 입력시 1차원 배열로 변경해줌 
Ans.values
# 각 값에대한 데이터 추출
Ans.values /Ans.sum(axis=1).values.reshape(-1,1)
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개의 댓글