Chapter 01에서 배울 내용

  1. DataFrame: Pandas의 기본 데이터 형태
  2. DataFrame 합치기
  3. DataFrame 정보 요약하기
  4. DataFrame의 열(column) 선택하기
  5. DataFrame의 행(row) 선택하기(basic)
  6. DataFrame의 행(row) 선택하기(filtering)
  7. 분류하기(Sorting)
  8.  DataFrame 통계 기술하기
  9. 데이터 질 평가(quality check)
  10. 행 이름 수정하기
  11. 이상치(outlier) 처리하기
  12. 파일 불러오기/내보내기

09 Quality check

Remove duplicate data

df = users.append(df.iloc[0], ignore_index=True)
print(df.duplicated()) # Series of booleans
# (True if a row is identical to a previous row)
df.duplicated().sum() # count of duplicates
df[df.duplicated()] # only show duplicates
df.age.duplicated() # check a single column for duplicates
df.duplicated(['age', 'gender']).sum() # specify columns for finding duplicates
df = df.drop_duplicates() # drop duplicate rows

Missing data

# Missing values are often just excluded
df = users.copy()
df.describe(include='all') # excludes missing values
# find missing values in a Series
df.height.isnull() # True if NaN, False otherwise
df.height.notnull() # False if NaN, True otherwise
df[df.height.notnull()] # only show rows where age is not NaN
df.height.isnull().sum() # count the missing values
# find missing values in a DataFrame
df.isnull() # DataFrame of booleans
df.isnull().sum() # calculate the sum of each column

Strategy 1: drop missing values

df.dropna() # drop a row if ANY values are missing
df.dropna(how='all') # drop a row only if ALL values are missing

Strategy 2: fill in missing values

df.height.mean()
df = users.copy()
df.ix[df.height.isnull(), "height"] = df["height"].mean()
print(df)

10 Rename values

df = users.copy()
print(df.columns)
df.columns = ['age', 'genre', 'travail', 'nom', 'taille']
df.travail = df.travail.map({ 'student':'etudiant', 'manager':'manager',
'engineer':'ingenieur', 'scientist':'scientific'})
assert df.travail.isnull().sum() == 0
df['travail'].str.contains("etu|inge")

11 Dealing with outliers

size = pd.Series(np.random.normal(loc=175, size=20, scale=10))
# Corrupt the first 3 measures
size[:3] += 500

Based on parametric statistics: use the mean

랜덤 변수가 정규분포를 따른다고 가정한 후 표준편차의 3배를 넘는 범위에 있는 데이터를 삭제한다. 1 sd 이내에는 68.27%의 데이터가 속하여 3 sd 이내에는 99.73%의 데이터가 속한다.

size_outlr_mean = size.copy()
size_outlr_mean[((size - size.mean()).abs() > 3 * size.std())] = size.mean()
print(size_outlr_mean.mean()

Based on non-parametric statistics: use the median

비모수 방법으로 중앙값을 기반으로한 Median absolute deviation(MAD)을 이용할 수 있다.

mad = 1.4826 * np.median(np.abs(size - size.median()))
size_outlr_mad = size.copy()

size_outlr_mad[((size - size.median()).abs() > 3 * mad)] = size.median()
print(size_outlr_mad.mean(), size_outlr_mad.median())

12 File I/O

csv

import tempfile, os.path
tmpdir = tempfile.gettempdir()
csv_filename = os.path.join(tmpdir, "users.csv")
users.to_csv(csv_filename, index=False)
other = pd.read_csv(csv_filename)

Read csv from url

url = 'https://raw.github.com/neurospin/pystatsml/master/data/salary_table.csv'
salary = pd.read_csv(url)

Excel

xls_filename = os.path.join(tmpdir, "users.xlsx")
users.to_excel(xls_filename, sheet_name='users', index=False)

pd.read_excel(xls_filename, sheetname='users')

# Multiple sheets
with pd.ExcelWriter(xls_filename) as writer:
users.to_excel(writer, sheet_name='users', index=False)
df.to_excel(writer, sheet_name='salary', index=False)

pd.read_excel(xls_filename, sheetname='users')
pd.read_excel(xls_filename, sheetname='salary')
카테고리: Statistics

0개의 댓글

답글 남기기

Avatar placeholder

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다