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 값의 데이터 출력df.select_dtypes (exclude=object).columns
df.select_dtypes (include=object).columns
df['val'].quantile (0.75) - df['val'].quantile(0.25)
df['val'].nunique ()
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] #짝수번째 columnsisin
lst=[1,2,3,4,5] df.loc [ df.newP.isin (lst) ]
df.sort_values ('newP', ascending=False).reset_index(drop=True)
# 중복 제거, keep= 없는 경우 첫번째 남김
df.drop_duplicates ('name', keep='last')
#빈도수 구하기 : 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의 개수로 변형함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)
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 columnsapply to DataFrameCol
def check (x): if x == 'M': return 1 else: return 0 df.col1.apply (check)
dataFrame.apply와dataFrame.Col.apply구분하기
lambda 식은 map과 apply 결과가 동일함이 글은 제로베이스 데이터 분석 취업 스쿨의 강의자료 일부를 발췌하여 작성되었습니다.