LiJell's 성장기

19.python_pandas_practice 본문

Bigdata/파이썬_Python

19.python_pandas_practice

All_is_LiJell 2022. 1. 10. 23:10
반응형

Modified on Jan 10 2022
# -- coding: utf-8 --
"""
Created on Wed Dec 29 15:04:23 2021

@author: hanju
"""

판다스 연습문제

df1 = pd.read_csv("./data/cancer_test.csv")
df1.columns
df1.dtypes

df1.head()
df1.info()
df1.describe()

1. radius_mean, texture_mean, texture_se , smoothness_se

  • NA인 행을 제거하고 총 행의 수 리턴
df1['radius_mean'].isnull().sum()
df1['texture_mean'].isnull().sum()
df1['texture_se'].isnull().sum()
df1['smoothness_se'].isnull().sum()
# null 4개가 있다

vbool =df1['radius_mean'].isnull() & df1['texture_mean'].isnull() & df1['texture_se'].isnull() & df1['smoothness_se'].isnull()
vbool.sum() # 컬럼 4개가 모두 NA인 행의 수

df1
df1.loc[vbool,:] # 컬럼 4개가 모두 NA인 행 확
'''
           id diagnosis  ...  symmetry_worst  fractal_dimension_worst
285   8912521    Benign  ...          0.2505                  0.06431
290  89143602    Benign  ...          0.2272                  0.08799
294    891716    Benign  ...          0.2369                  0.06922
299    892399    Benign  ...          0.2227                  0.06777
'''
df1.shape # (569, 32)
df1.shape [0] #행의 개수
df1.shape [1] #열의 개수

df1.shape[0]-vbool.sum() # 565 - 4 (565--> not null 행 수)

print(df1.shape[0]-vbool.sum())
# 565

#
df1.dropna(subset=['radius_mean', 'texture_mean', 'texture_se', 'smoothness_se'], how='all')
'''
           id  diagnosis  ...  symmetry_worst  fractal_dimension_worst
0      842302  Malignant  ...          0.4601                  0.11890
1      842517  Malignant  ...          0.2750                  0.08902
2    84300903  Malignant  ...          0.3613                  0.08758
3    84348301  Malignant  ...          0.6638                  0.17300
4    84358402  Malignant  ...          0.2364                  0.07678
..        ...        ...  ...             ...                      ...
564    926424  Malignant  ...          0.2060                  0.07115
565    926682  Malignant  ...          0.2572                  0.06637
566    926954  Malignant  ...          0.2218                  0.07820
567    927241  Malignant  ...          0.4087                  0.12400
568     92751     Benign  ...          0.2871                  0.07039

[565 rows x 32 columns]
'''
df1.dropna(subset=['radius_mean', 'texture_mean', 'texture_se', 'smoothness_se'], how='all').shape[0]
nrow = df1.dropna(subset=['radius_mean', 'texture_mean', 'texture_se', 'smoothness_se'], how='all').shape[0]

print(nrow)
# 565

2. concavity_mean 의 standard scaling (표준화) 후, 결과가 0.1 이상인 값의 개수 출력해줘

  • standard scaling(표준화) = (원 데이터 - 평균) / 표준편차
  • minmax scaling = (원 데이터 - 최소) / (최대-최소)
standard way
df1.columns
(df1['concavity_mean']-df1['concavity_mean'].mean()) / df1['concavity_mean'].std()
vscale = (df1['concavity_mean']-df1['concavity_mean'].mean()) / df1['concavity_mean'].std()

'''
0      2.650542
1     -0.023825
2      1.362280
3      1.914213
4      1.369806

564    1.945573
565    0.692434
566    0.046547
567    3.294046
568   -1.113893
Name: concavity_mean, Length: 569, dtype: float64
'''
(vscale > 0.1 ).sum() # 207건 (vscale > 0.1 ) 이 T/F 값으로 나오기 때문에 sum으로 개수 확인 가능

rank 참고

_df = pd.DataFrame(
    {'name': ['KIM', 'LEE', 'SMITH','BROWN', 'MILLER'],
     'age': [24, 32, 43, 24, np.nan]})

'''
     name   age
0     KIM  24.0
1     LEE  32.0
2   SMITH  43.0
3   BROWN  24.0
4  MILLER   NaN

'''

동점자 처리 기준 5가지

_df['rank_average'] = _df['age'].rank(method='average') #default
'''
0    1.5
1    3.0
2    4.0
3    1.5
4    NaN
Name: rank_average, dtype: float64
'''

_df['rank_min'] = _df['age'].rank(method='min')
'''
0    1.0
1    3.0
2    4.0
3    1.0
4    NaN
Name: rank_min, dtype: float64
'''

_df['rank_max'] = _df['age'].rank(method='max')
'''
0    2.0
1    3.0
2    4.0
3    2.0
4    NaN
Name: rank_max, dtype: float64
'''

_df['rank_first'] = _df['age'].rank(method='first') # 먼저 나온애 우선으로
'''
0    1.0
1    3.0
2    4.0
3    2.0
4    NaN
Name: rank_first, dtype: float64
'''

_df['rank_dense'] = _df['age'].rank(method='dense')
# dense는 min 유사, dense는 1순위가 2명이라고 3번째 사람이 3등이 아닌 2등
'''
0    1.0
1    2.0
2    3.0
3    1.0
4    NaN
Name: rank_dense, dtype: float64
'''


_df
'''
     name   age  rank_first  rank_dense  rank_average  rank_min  rank_max
0     KIM  24.0         1.0         1.0           1.5       1.0       2.0
1     LEE  32.0         3.0         2.0           3.0       3.0       3.0
2   SMITH  43.0         4.0         3.0           4.0       4.0       4.0
3   BROWN  24.0         2.0         1.0           1.5       1.0       2.0
4  MILLER   NaN         NaN         NaN           NaN       NaN       NaN
'''
_df['age'].rank(method='first') 
# default가 ascending이기 때문에 나이 적은 애가 1등
'''
0    1.0
1    3.0
2    4.0
3    2.0
4    NaN
Name: age, dtype: float64
'''

_df['age'].rank(method='first', ascending=False) 
# descending이라 나이가 많은 사람이 1등
'''
0    3.0
1    2.0
2    1.0
3    4.0
4    NaN
Name: age, dtype: float64
'''

3. 이상치 건 수 확인

  • texture_se 의 상위 10% 값 (NA를 제외한 건수의 10%)을 이상치로 가정한다.
  • 10%를 제외한 값의 최대값으로 수정한 후 평균을 소수점 둘째자리로 반올림하여 출력
  • 이상치 건수 확인
df1['texture_se'].dropna()
'''
0      0.9053
1      0.7339
2      0.7869
3      1.1560
4      0.7813

564    1.2560
565    2.4630
566    1.0750
567    1.5950
568    1.4280
Name: texture_se, Length: 565, dtype: float64
'''
df1['texture_se'].dropna().shape[0] (행 개수)
# 565
nx = int(np.trunc(df1['texture_se'].dropna().shape[0] * 0.1))
# 56.0
type(nx) #int

이상치를 제외한 나머지 >> 평균

df1['texture_se'].rank(ascending = False, method = 'first')
vrank = df1['texture_se'].rank(ascending = False, method = 'first')
df1['texture_se'].rank(ascending = False, method = 'first')

df1.loc[vrank > nx, 'texture_se'] #정상치 데이터
vmax = df1.loc[vrank > nx, 'texture_se'].max() # 정상치 데이터 최대값

df1.loc[~(vrank > nx), 'texture_se']
df1.loc[vrank <= nx, 'texture_se'] # 이상치 데이터
df1['texture_se'].sort_values(ascending = False)[:nx]

이상치 데이터를 vmax로 치환해서 이상치 없에기

df1.loc[vrank <= nx, 'texture_se'] = vmax

round(df1['texture_se'].mean(), 2)

4. symmetry_mean의 결측치를 최소값으로 수정한 후 평균을 소수점 둘째 자리로 반올림하여 출력해 주세요

df1['symmetry_mean'].min() 
# '-'
# 어라? 문자열이 있네 -> 제거해줘야지

from numpy import nan as NA 
df1['symmetry_mean'].replace('-', NA)
df1['symmetry_mean'] = df1['symmetry_mean'].replace('-', NA)
df1['symmetry_mean'].astype(float)
# ValueError: could not convert string to float: '.' 
# 아 '.' 도있네
df1['symmetry_mean'].replace('.', NA)
df1['symmetry_mean'] = df1['symmetry_mean'].replace('.', NA)
df1['symmetry_mean'].astype(float)
# ValueError: could not convert string to float: 'pass'
df1['symmetry_mean'].replace('pass', NA)
df1['symmetry_mean'] = df1['symmetry_mean'].replace('pass', NA)
df1['symmetry_mean'].astype(float)
df1['symmetry_mean'] = df1['symmetry_mean'].astype(float)
df1['symmetry_mean']

#최소값 확인 
vmin = df1['symmetry_mean'].min() 
# 0.106

# 결측치 수정
df1['symmetry_mean'].fillna(vmin)
df1['symmetry_mean']=df1['symmetry_mean'].fillna(vmin)

# 평균 확인
print(round(df1['symmetry_mean'].mean(),2))  # 0.18
반응형

'Bigdata > 파이썬_Python' 카테고리의 다른 글

Python Extras  (0) 2022.02.14
Pandas Styling: 판다스 스타일링  (2) 2022.02.11
18.python_visualization  (0) 2022.01.10
17.python_datetime_expression  (0) 2022.01.10
16.python_NA_missing_duplicate_value  (0) 2022.01.10
Comments