03 Grouping
https://www.datamanim.com/dataset/99_pandas/pandasMain.html
판다스 연습 튜토리얼 — DataManim
Question 43 df의 데이터 중 new_price값이 lst에 해당하는 경우의 데이터 프레임을 구하고 그 갯수를 출력하라 lst =[1.69, 2.39, 3.39, 4.45, 9.25, 10.98, 11.75, 16.98]
www.datamanim.com
Question 44
데이터를 로드하고 상위 5개 컬럼을 출력하라
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/pandas/main/AB_NYC_2019.csv')
Ans =df.head(5)
Ans
Question 45
데이터의 각 host_name의 빈도수를 구하고 host_name으로 정렬하여 상위 5개를 출력하라
Ans = df.groupby('host_name').size()
Ans.head(5)
Ans = df.host_name.value_counts().sort_index()
Ans.head(5)
df.groupby('').size()
df.특정변수.value_counts().sort_index()
Question 46
데이터의 각 host_name의 빈도수를 구하고 빈도수 기준 내림차순 정렬한 데이터 프레임을 만들어라.
빈도수 컬럼은 counts로 명명하라
Ans = df.groupby('host_name').size().\
to_frame().rename(columns={0:'counts'}).\
sort_values('counts',ascending=False)
Ans.head(5)
Question 47
neighbourhood_group의 값에 따른 neighbourhood컬럼 값의 갯수를 구하여라
Ans = df.groupby(['neighbourhood_group','neighbourhood'], as_index=False).size()
Ans.head(4)
Question 48
neighbourhood_group의 값에 따른 neighbourhood컬럼 값 중 neighbourhood_group그룹의 최댓값들을 출력하라
Ans= df.groupby(['neighbourhood_group','neighbourhood'], as_index=False).size()\
.groupby(['neighbourhood_group'], as_index=False).max()
Ans
Question 49
neighbourhood_group 값에 따른 price값의 평균, 분산, 최대, 최소 값을 구하여라
Ans = df[['neighbourhood_group','price']].groupby('neighbourhood_group').agg(['mean','var','max','min'])
Ans
groupby('').agg(['mean', 'var', 'max', 'min])
Question 50
neighbourhood_group 값에 따른 reviews_per_month 평균, 분산, 최대, 최소 값을 구하여라
Ans = df[['neighbourhood_group','reviews_per_month']].groupby('neighbourhood_group').agg(['mean','var','max','min'])
Ans
Question 51
neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 구하라
Ans = df.groupby(['neighbourhood','neighbourhood_group']).price.mean()
Ans
Question 52
neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 계층적 indexing 없이 구하라
Ans = df.groupby(['neighbourhood','neighbourhood_group']).price.mean().unstack()
Ans
.unstack() : 계층적 indexing 없이 구하기
index에 있던 값을 column으로 올려준다
Question 53
neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 계층적 indexing 없이 구하고 nan 값은 -999값으로 채워라
Ans = df.groupby(['neighbourhood','neighbourhood_group']).price.mean().unstack().fillna(-999)
Ans.head(4)
Question 54
데이터중 neighbourhood_group 값이 Queens값을 가지는 데이터들 중 neighbourhood 그룹별로 price값의 평균, 분산, 최대, 최소값을 구하라
Ans = df[df.neighbourhood_group=='Queens'].groupby(['neighbourhood']).price.agg(['mean','var','max','min'])
Ans.head(4)
Question 55
데이터중 neighbourhood_group 값에 따른 room_type 컬럼의 숫자를 구하고 neighbourhood_group 값을 기준으로 각 값의 비율을 구하여라
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