Moonie

[빅데이터 분석기사 실기] 데이터 전처리 python 100 - 5 본문

공부/자격증

[빅데이터 분석기사 실기] 데이터 전처리 python 100 - 5

Moonie' 2024. 10. 22. 01:16
반응형

아래 블로그를 참고하여 진행했습니다.

https://www.datamanim.com/dataset/99_pandas/pandasMain.html#google_vignette

 

 

이전 블로그에 이어서 작성했습니다.

https://moonie.tistory.com/36

 

[빅데이터 분석기사 실기] 데이터 전처리 python 100 - 4

아래 블로그를 참조해서 진행했습니다.https://www.datamanim.com/dataset/99_pandas/pandasMain.html    해당 글에 이어서 진행한다.https://moonie.tistory.com/34 [빅데이터 분석기사 실기] 데이터 전처리 python 100 - 3

moonie.tistory.com

 

 

Question 41 df의 데이터 중 item_name 값이 N으로 시작하는 데이터를 모두 추출하라

ans = df[df.item_name.str.startswith('N')]
ans.head(3)

 

Question 42 df의 데이터 중 item_name 값의 단어갯수가 15개 이상인 데이터를 인덱싱하라

ans = df[df.item_name.str.len() >=15]
ans.head(5)

 

len() 함수를 통해 글자의 개수데이터를 얻음

 

Question 43  df의 데이터 중 new_price값이 lst에 해당하는 경우의 데이터 프레임을 구하고 그 갯수를 출력하라 lst =[1.69, 2.39, 3.39, 4.45, 9.25, 10.98, 11.75, 16.98]

lst =[1.69, 2.39, 3.39, 4.45, 9.25, 10.98, 11.75, 16.98]
ans = df.loc[df.new_price.isin(lst)]
display(ans.head(3))
print(len(ans))

 

 

03_Grouping

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

DataUrl = 'https://raw.githubusercontent.com/Datamanim/pandas/main/AB_NYC_2019.csv'
df = pd.read_csv(DataUrl)
df.head(5)

 

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

ans = df.groupby('host_name').size()
ans.head(5)

 

 

  • df.groupby('host_name'):
    • df 데이터프레임에서 host_name 열을 기준으로 데이터를 그룹화합니다. 즉, 동일한 host_name 값을 가진 행들을 하나의 그룹으로 묶습니다.
  • .size():
    • 그룹화된 각 그룹의 크기(행의 개수)를 반환합니다. 이 메서드는 각 그룹에 포함된 행의 수를 계산하여 반환합니다.

 

ans = df.host_name.valuecounts().sort_index()
ans.head(5)
  • df.host_name:
    • df라는 데이터프레임에서 host_name이라는 열을 선택합니다. 즉, 해당 열에 포함된 데이터를 추출하는 단계입니다.
  • value_counts():
    • host_name 열에 들어 있는 각 값의 빈도(몇 번 나타나는지)를 계산합니다. 즉, host_name에 포함된 고유 값들에 대해 각 값이 데이터프레임에서 몇 번 등장했는지를 셉니다. 결과는 고유 값과 해당 값의 빈도가 포함된 Pandas 시리즈로 반환됩니다.
  • sort_index():
    • value_counts()가 반환한 시리즈는 기본적으로 빈도가 많은 순서대로 정렬되어 있습니다. 하지만 sort_index()를 사용하면 인덱스 기준으로 정렬됩니다. 즉, host_name 값을 알파벳 순서(혹은 숫자일 경우 숫자 순서)로 정렬합니다.

 

 

 

Question 46 데이터의 각 host_name의 빈도수를 구하고 빈도수 기준 내림차순 정렬한 데이터 프레임을 만들어라. 빈도수 컬럼은 counts로 명명하라

ans = df.groupby('host_name').size().\
        to_frame().rename(columns={0:'counts'}).\
        sort_values('counts',ascending=False)

 

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

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

  • df.groupby(['neighbourhood_group', 'neighbourhood']):
    • 데이터프레임을 neighbourhood_group과 neighbourhood라는 두 개의 열을 기준으로 그룹화합니다.

 

  • as_index=False:
    • 그룹화된 열(neighbourhood_group, neighbourhood)이 인덱스로 설정되지 않고 일반 열로 유지되도록 합니다.
  • .size():
    • 그룹화된 각 조합에 대해 **그룹의 크기(즉, 각 그룹에 포함된 행의 개수)**를 계산합니다.
  • groupby(['neighbourhood_group']):
    • 첫 번째 그룹화 결과를 다시 neighbourhood_group만 기준으로 그룹화합니다.
    • 각 neighbourhood_group 내에서 가장 큰 값을 찾기 위해 그룹화된 상태로 나눕니다.
  • .max():
    • 각 neighbourhood_group에 대해 size 값이 가장 큰 행(즉, 각 neighbourhood_group 내에서 가장 큰 neighbourhood 그룹)을 선택합니다.

 

Question 48 neighbourhood_group의 값에 따른 neighbourhood컬럼 값 중 neighbourhood_group그룹의 최댓값들을 출력하라

 

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

 

 

  • df.groupby(['neighbourhood_group', 'neighbourhood']):
    • neighbourhood_group과 neighbourhood 열을 기준으로 데이터를 그룹화합니다.
  • as_index=False:
    • 기본적으로 groupby() 함수는 그룹화 기준이 되는 열을 인덱스로 설정하는데, 이 옵션을 사용하면 그룹화 기준 열들이 인덱스로 설정되지 않고 일반 열로 유지됩니다.
  • .size():
    • 각 그룹의 행 개수(즉, 그룹에 속하는 데이터 개수)를 계산합니다.

 

  • groupby(['neighbourhood_group']):
    • neighbourhood_group을 기준으로 다시 그룹화합니다. 이번에는 각 neighbourhood_group에서 하나의 neighbourhood를 선택하기 위한 작업입니다.
  • as_index=False:
    • 다시 한 번 인덱스가 아니라, neighbourhood_group을 일반 열로 유지하기 위한 옵션입니다.
  • .max():
    • max() 함수는 각 neighbourhood_group에서 size 값이 가장 큰 행을 반환합니다. size가 클수록 더 큰 그룹이므로, 각 neighbourhood_group에서 가장 큰 neighbourhood와 그 크기를 반환하는 것입니다.

 

 

 

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

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

.agg(['mean', 'var', 'max', 'min']):

  • **agg()**는 그룹화된 데이터를 가지고 여러 통계적 집계 함수를 한 번에 적용할 수 있는 메서드입니다.
  • **['mean', 'var', 'max', 'min']**은 price 열에 대해 다음의 통계 함수들을 계산합니다:
    • mean: 각 neighbourhood_group의 평균 가격을 계산합니다.
    • var: 각 neighbourhood_group의 가격에 대한 분산(variance)을 계산합니다. 분산은 데이터가 평균으로부터 얼마나 퍼져 있는지를 나타내는 지표입니다.
    • max: 각 neighbourhood_group에서 가장 높은 가격을 찾습니다.
    • min: 각 neighbourhood_group에서 가장 낮은 가격을 찾습니다.

 

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

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

 

Question 51 neighbourhood 값과 neighbourhood_group 값에 따른 price 의 평균을 구하라

df.groupby(['neighbourhood','neighbourhood_group']).price.mean()

 

 

 

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

 

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

 

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

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

 

 

 

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

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

 

 

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

Ans = df[['neighbourhood_group','room_type']].groupby(['neighbourhood_group','room_type']).size().unstack()
# 데이터프레임을 float로 변환
Ans = Ans.astype(float)
# Ans의 각 행에 대한 값을 비율로 계산
Ans.loc[:,:] = (Ans.values / Ans.sum(axis=1).values.reshape(-1,1))

 

.unstack():

  • 그룹화된 결과는 기본적으로 neighbourhood_group과 room_type이 멀티 인덱스 형태로 나타납니다. 이때 .unstack()을 사용하면 room_type이 **열(column)**로 변환되어 데이터프레임 형태로 정리됩니다.
  • 결과는 neighbourhood_group이 행 인덱스, room_type이 열 인덱스가 되고, 각 셀에는 해당 조합에 대한 데이터의 개수가 들어갑니다.

astype(float):

  • Ans 데이터프레임의 데이터 유형을 **정수(int)**에서 **부동소수점(float)**으로 변환합니다.
  • 이렇게 변환하는 이유는 이후의 비율 계산에서 소수점이 포함된 값을 저장할 수 있도록 하기 위함입니다.
  • 데이터의 크기(개수)는 정수로 표현되지만, 비율을 계산하면 소수점 값이 생기므로 이를 처리하기 위해 데이터 타입을 float으로 변경해야 합니다.
  • 지정하지 않으면 에러가 나타납니다.

Ans.sum(axis=1):

  • Ans.sum(axis=1)는 각 행의 합을 계산합니다. 즉, 각 neighbourhood_group에서 모든 room_type의 값(즉, 데이터의 개수)을 더한 값을 구합니다.

.values.reshape(-1, 1):

  • reshape(-1, 1)는 배열을 세로로 다시 정렬합니다. 즉, 각 neighbourhood_group의 행 합을 하나의 열로 변환합니다.
  • 이렇게 하면 각 neighbourhood_group의 합을 모든 room_type에 대해 나누어줄 수 있는 형태가 됩니다.

Ans.values / Ans.sum(axis=1).values.reshape(-1, 1):

  • 이 단계에서는 각 room_type의 값해당 neighbourhood_group의 전체 값 합계로 나누어 비율을 계산합니다.

Ans.loc[:, :] = ...:

  • Ans.loc[:, :]는 Ans 데이터프레임의 모든 값을 위에서 계산한 비율 값으로 덮어씌우는 작업을 수행합니다.
반응형
Comments