python 기초 (분석가 ver)

문병두·2024년 11월 20일

python

목록 보기
1/5

python 기초 분석가

data read

DriveUrl = 'https://drive.google.com/uc?id=1kXeXtquJ-TDHa6c4tx-iOwJmjufyqe2P'

csv 파일 읽어오기
df = pd.read_csv(DriveUrl)
type(df)

상위 5개의 행 출력

df.head()
() 기본 5개 행 출력

데이터 행과 열의 갯수 파악

print(df.shape)

n번째 컬럼 출력

df.columns[n]

n은 0부터 세기 시작

컬럼이 한글이기에 적절한 처리

import pandas as pd
DriveUrl = 'https://drive.google.com/uc?id=1PUmB7uspU5R-bYDtKW_6eodBTwCVYG_s'
df = pd.read_csv(DriveUrl, encoding = 'euc-kr')
type(df)

마지막 행 출력

df.tail()

각 컬럼의 결측치 숫자를 파악

df.isnull().sum()

각 컬럼의 데이터수, 데이터타입을 한번에 확인

df.info()

각 수치형 변수의 분포(사분위, 평균, 표준편차, 최대 , 최소)를 확인

df.describe()

특정 컬럼 값 출력

df['컬럼']

컬럼 유일값 갯수

df['컬럼'].nunique()

컬럼 유일값 출력
df['컬럼'].unique()

filtering

컬럼 값이 3인 데이터를 추출하여 첫 5행을 출력

df[df['컬럼']==3].head()

컬럼 값이 3인 데이터를 추출하여 index를 0부터 정렬하고 첫 5행을 출력

df[df['컬럼']==3].head().reset_index(drop=True)

두개의 컬럼으로 구성된 새로운 데이터 프레임을 정의하라

df2= df[['컬럼','컬럼']]

컬럼이 5이하의 값을 가지는 데이터프레임을 추출하고, 전체 갯수

len(df[df['컬럼']<=5])

new_price값이 9 이하이고 item_name 값이 Chicken Salad Bowl 인 데이터 프레임을 추출

df.loc[(df.item_name =='Chicken Salad Bowl') & (df.new_price <= 9)]

오름차순으로 정리하고 index를 초기화 하여라

df.sort_values('new_price').reset_index(drop=True)

df의 item_name 컬럼 값중 Chips 포함하는 경우의 데이터를 출력

df.loc[df.item_name.str.contains('Chips')]

df의 item_name 컬럼 값이 Steak Salad 또는 Bowl 인 데이터

df.loc[(df.item_name =='Steak Salad') | (df.item_name =='Bowl')]

item_name를 기준으로 중복행이 있으면 제거하되 첫번째 케이스만 남겨라
Ans.drop_duplicates('item_name')

df의 데이터 중 item_name의 값이 Izze 데이터를 Fizzy Lizzy로 수정

df.loc[df.item_name =='Izze','item_name'] = 'Fizzy Lizzy'

df의 데이터 중 choice_description 값이 NaN 인 데이터를 NoData 값으로 대체하라(loc 이용)

df.loc[df.choice_description.isnull(),'choice_description'] ='NoData'

df의 데이터 중 choice_description 값에 Vegetables 들어가지 않는
df.loc[~df.choice_description.str.contains('Vegetables')]
~ 부정
없으면 긍정

df의 데이터 중 item_name 값이 N으로 시작하는 데이터
df[df.item_name.str.startswith('N')]

df의 데이터 중 item_name 값의 단어갯수가 15개 이상인 데이터
df[df.item_name.str.len() >=15]

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))

Grouping

SQL groupby 마찬가지로 컬럼 그룹지어 데이터 출력

neighbourhood_group의 값에 따른 neighbourhood컬럼 값의 갯수
df.groupby(['neighbourhood_group','neighbourhood'], as_index=False).size()

neighbourhood_group 값에 따른 price값의 평균, 분산, 최대, 최소 값
df.groupby('neighbourhood_group')['price'].agg(['mean','var','max','min'])

neighbourhood_group 값에 따른 reviews_per_month 평균, 분산, 최대, 최소 값

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

Apply map

함수를 이용하여 출력

Income_Category의 카테고리를 map 함수를 이용하여 다음과 같이 변경하여 newIncome 컬럼에 매핑하라

dic = {
'Unknown' : 'N',
'Less than $40K' : 'a',
'$40K - $60K' : 'b',
'$60K - $80K' : 'c',
'$80K - $120K' : 'd',
'$120K +' : 'e'
}

df['newIncome'] = df.Income_Category.map(lambda x: dic[x])
income_category 값을 dic 함수를 받아 값을 치환함

Ans = df[['newIncome', 'Income_Category']]
Ans.head()

apply
함수를 정의하여 apply에 함수를 호출함
def changeCategory(x):
if x =='Unknown':
return 'N'
elif x =='Less than $40K':
return 'a'
elif x =='$40K - $60K':
return 'b'
elif x =='$60K - $80K':
return 'c'
elif x =='$80K - $120K':
return 'd'
elif x =='$120K +' :
return 'e'

df['newIncome'] =df.Income_Category.apply(changeCategory)

Ans = df[['newIncome', 'Income_Category']]

Education_Level의 값중 Graduate단어가 포함되는 값은 1 그렇지 않은 경우에는 0으로 변경하여 newEduLevel 컬럼을 정의하고 빈도수를 출력하라

df['newEduLevel'] = df.Education_Level.map(lambda x : 1 if 'Graduate' in x else 0)
Ans = df['newEduLevel'].value_counts()

Credit_Limit 컬럼값이 4500 이상인 경우 1 그외의 경우에는 모두 0으로 하는 newLimit 정의하라. newLimit 각 값들의 빈도수를 출력하라

map
df.Credit_Limit.map(lambda x : 1 if x>=4500 else 0)

apply
df.Credit_Limit.apply(lambda x : 1 if x>=4500 else 0)

Gender 컬럼값 M인 경우 male F인 경우 female로 값을 변경하여 Gender 컬럼에 새롭게 정의하라

def changeGender(x):
if x =='M':
return 'male'
else:
return 'female'
df['Gender'] = df.Gender.apply(changeGender)

profile
데이터분석가

0개의 댓글