스터디노트 5월 20일

Jenny·2024년 5월 19일

01 Data read

  • 데이터 읽어오기
import pandas as pd
df = pd.read_csv (url, encoding='euc-kr')
  • df.shape (행, 열) 출력
  • df.columns columns list 출력
  • df.head() 상위 5개 데이터 출력
  • df.tail(3) 하위 3개 데이터 출력
  • df.isnull().sum() 각 열의 null개수 합 출력
  • df.info() columns별 type, size 출력
  • df.describe() columns별 statistics 출력
  • df.iloc [:,5].dtype 6번째 컬럼의 데이터 타입 출력
  • df.iloc [2,5] 3행 6열의 데이터 출력
  • df.loc [value] value 값의 데이터 출력
  • Numerical columns
df.select_dtypes (exclude=object).columns
  • Categorical columns
df.select_dtypes (include=object).columns
  • 4분위 범위 관련 출력
df['val'].quantile (0.75) - df['val'].quantile(0.25)
  • unique한 개수 출력
df['val'].nunique ()

02 Data filtering & sorting

  • Data filtering
df.loc [ df['val' ==3] ].head().reset_index(drop=True)
df.loc [ df.name == 'o' ]
df.loc [ ~df.name.str.contains('o') ]
df.loc [ df.newP >= df.newP.mean () ]
df.loc [ df.name == 'o', 'name'] = 'A'		#name 검색 후 'A'로 수정

str functions

name.str.contains('o')
name.str.startswith('w')
name.str.len()
name.str[1:].astype('float') #type을 float로 설정

iloc

df.iloc [:, ::2]		#짝수번째 columns

isin

lst=[1,2,3,4,5]
df.loc [ df.newP.isin (lst) ]
  • Data sorting
df.sort_values ('newP', ascending=False).reset_index(drop=True)

# 중복 제거, keep= 없는 경우 첫번째 남김
df.drop_duplicates ('name', keep='last')

03 Grouping

#빈도수 구하기 : size
df.host.value_counts().to_frame().sort_index()
df.groupby('host').size().to_frame()

#col1 값에 따른 col2 값의 개수
df.groupby (['col1', 'col2'], as_index=False).size()

#groupby를 이용하여 pivot table처럼 출력
df.groupby (['col1', 'col2']).price.mean().unstack().fillna(0)
  • df.values Dataframe의 값을 array형태로 나타냄
  • df.sum(axis=1) each col값을 합함
  • np.reshape (-1,1) col을 1개로 했을 때 알맞은 row의 개수로 변형함

04 Apply, map

  • map
alpha = { 'Unknown' : 'N', 'Less' : 'a'}
df['new'] = df.colName.map (lambda x: alpha[x])

Same results

df.colName.map (lambda x : 1 if 'Graduate' in x else 0)
np.where (df.colName.str.contains ('Graduate'), 1, 0)
  • apply
def alphaFunc (x):
	if x == 'Unknown':
    	return 'N'
    elif x == 'Less':
    	return 'a'
df['new'] = df.colName.apply (alphaFunc)

apply to DataFrame & axis

def check (x):
	if x.Col1 == 'M' and x.Col2 == 'P':
    	return 1
     else:
     	return 0
df.apply (check, axis=1)	## apply to each columns

apply to DataFrameCol

def check (x):
	if x == 'M':
    	return 1
    else:
    	return 0
df.col1.apply (check)
  • dataFrame.applydataFrame.Col.apply 구분하기
  • lambda 식은 map과 apply 결과가 동일함


이 글은 제로베이스 데이터 분석 취업 스쿨의 강의자료 일부를 발췌하여 작성되었습니다.

profile
I like to movie movie

0개의 댓글