Post

[KT Aivle 3기 AI] 4일차. (3) Pandas

1. 개요

KT Aivle School 3기 AI 4일차

  • 주제 : Pandas
  • 강사 : 한기영 강사님
  • 내용 : Python Library 중 하나인 Pandas에 대하여 설명해주셨다. 대학교에서 수업 때 배운 적이 있어 수월하게 배울 수 있었다. 이전에 내가 정리해놓은 것과 함께 이번 수업내용을 토대로 Pandas에 대해 정리해보려 한다.

2. Pandas

  • 구조화된 데이터 처리를 지원하는 Python 라이브러리
  • 고성능 array 계산 라이브러리인 Numpy와 통합하여, 강력한 스프레드시트처리 기능을 제공
  • 인덱싱, 연산용 함수, 전처리 함수 등을 제공함
  • 데이터 처리 및 통계 분석을 위해 사용

1) Series

  • 하나의 정보에 대한 데이터들의 집합
  • index가 추가된 numpy
  • 데이터 프레임에서 하나의 열을 떼어낸 것.(1차원)
1
2
3
4
5
6
7
from pandas import Series, DataFrame
import pandas as pd
import numpy as np

list_data = [1,2,3,4,5]
example_obj = Series(data = list_data)
example_obj
1
2
3
4
5
6
0    1
1    2
2    3
3    4
4    5
dtype: int64
1
2
3
4
list_data = [1,2,3,4,5]
list_name = ["a","b","c","d","e"]
example_obj = Series(data = list_data, index = list_name)
example_obj
1
2
3
4
5
6
a    1
b    2
c    3
d    4
e    5
dtype: int64
1
2
3
dic_data = {"a":1 , "b":2, "c":3, "d":4, "e":5}
example_obj = Series(dic_data, dtype=np.float32, name="example_data")
example_obj
1
2
3
4
5
6
a    1.0
b    2.0
c    3.0
d    4.0
e    5.0
Name: example_data, dtype: float32
1
example_obj["a"]
1
1.0
1
example_obj.values
1
array([1., 2., 3., 4., 5.], dtype=float32)
1
example_obj.index
1
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
1
2
3
example_obj.name = "number"
example_obj.index.name = "alphabet"
example_obj
1
2
3
4
5
6
7
alphabet
a    1.0
b    2.0
c    3.0
d    4.0
e    5.0
Name: number, dtype: float32

2) DataFrame

  • 데이터 분석에서 가장 중요한 데이터 구조
  • 관계형 데이터베이스의 테이블 또는 엑셀 시트와 같은 형태(2차원 구조)
  • 변수들의 집합 -> 각 열을 변수라고 부름
  • 행 -> 의미 : 분석단위, 다른 말로 : 관측치, 샘플
  • 열 -> 의미 : 정보, 다른 말로 : 변수(feature, target)
  • Pandas 사용 목적이 데이터프레임을 사용하기 위한 목적으로 봐도 된다.
  • 데이터를 처리, 조회, 분석하는 가장 효율적인 방법이 데이터프레임을 사용하는 것
  • 일반적으로 접하게 되는 테이블 형태, 엑셀 형태로 생각하면 된다.
  • 직접 만들 수 있으나 보통은 csv 파일, 엑셀 파일 또는 DB에서 온다.

(1) DataFrame 생성

1
2
3
4
5
6
raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
      'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
      'age': [42, 52, 36, 24, 73],
      'city': ['San Francisco', 'Baltimore', 'Miami', 'Douglas', 'Boston']}
df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'city'])
df
first_namelast_nameagecity
0JasonMiller42San Francisco
1MollyJacobson52Baltimore
2TinaAli36Miami
3JakeMilner24Douglas
4AmyCooze73Boston

(2) CSV파일 읽어오기

[1] csv 파일로 부터 가져오기

1
2
3
4
5
# 데이터 읽어오기
data = pd.read_csv('airquality_simple.csv')  

# 상위 3행만 확인
data.head(3)
OzoneSolar.RWindTempMonthDay
041190.07.46751
136118.08.07252
212149.012.67453

[2] url로 가져오기

1
2
3
4
5
6
# 데이터 읽어오기
path = 'https://raw.githubusercontent.com/DA4BAM/dataset/master/Attrition_simple2.CSV'
data = pd.read_csv(path)  

# 상위 3개 확인
data.head(3)
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
00337817Male3Married11691No1114
1035181412Male4Single9362No1110
204261911Male1Married13348No1318

(3) DataFrame 탐색

  • 파일에서 불러온 데이터의 크기, 내용, 분포, 누락된 값 등을 확인
  • 확인된 내용을 통해 데이터 전처리 필요 여부를 결정
  • 데이터를 알아야 데이터를 분석할 수 있다!

[참고] 자주 사용할 만한 메서드들

  • head(): 상위 데이터 확인
  • tail(): 하위 데이터 확인
  • shape: 데이터프레임 크기
  • index: 인덱스 정보 확인
  • values: 값 정보 확인
  • columns: 열 정보 확인
  • dtypes: 열 자료형 확인
  • info(): 열에 대한 상세한 정보 확인
  • describe(): 기초통계정보 확인

[1] 상위, 하위 일부 데이터, 크기 확인

  • head(n), tail(n) 메소드를 사용해 앞 뒤 데이터를 확인
  • 개수를 지정하지 않으면 기본적으로 5개 행이 조회 됨
1) 상위 데이터 확인
1
data.head()
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
00337817Male3Married11691No1114
1035181412Male4Single9362No1110
204261911Male1Married13348No1318
304621204Female1Married17048No2328
41224593Male3Single3894No164
2) 하위 데이터 확인
1
data.tail(3)
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
119302991558Male3Married2451No185
11940292469Male3Married4649No144
119504316327Female4Married16064Yes2222
3) 크기 확인 .shape
  • (rows, cols) 값을 갖는 튜플 형태로 확인이 가능
  • 데이터를 분석할 때 처리할 데이터 양을 확인하는 목적으로 많이 사용
1
data.shape
1
(1196, 11)

[2] 열, 행 정보 보기

1) 열 확인
1
2
3
print(data.columns)
print()
print(data.columns.values) # np array 형태
1
2
3
4
5
6
7
8
Index(['Attrition', 'Age', 'DistanceFromHome', 'EmployeeNumber', 'Gender',
       'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'OverTime',
       'PercentSalaryHike', 'TotalWorkingYears'],
      dtype='object')

['Attrition' 'Age' 'DistanceFromHome' 'EmployeeNumber' 'Gender'
 'JobSatisfaction' 'MaritalStatus' 'MonthlyIncome' 'OverTime'
 'PercentSalaryHike' 'TotalWorkingYears']
1
2
# 데이터프레임을 리스트 함수에 넣으면 열 이름이 리스트로 반환됨.
list(data)
1
2
3
4
5
6
7
8
9
10
11
['Attrition',
 'Age',
 'DistanceFromHome',
 'EmployeeNumber',
 'Gender',
 'JobSatisfaction',
 'MaritalStatus',
 'MonthlyIncome',
 'OverTime',
 'PercentSalaryHike',
 'TotalWorkingYears']
2) 자료형 확인
  • int64: 정수형 데이터(int)
  • float64: 실수형 데이터(float)
  • object: 문자열 데이터(string)
1
data.dtypes
1
2
3
4
5
6
7
8
9
10
11
12
Attrition             int64
Age                   int64
DistanceFromHome      int64
EmployeeNumber        int64
Gender               object
JobSatisfaction       int64
MaritalStatus        object
MonthlyIncome         int64
OverTime             object
PercentSalaryHike     int64
TotalWorkingYears     int64
dtype: object
1
2
# 열 자료형, 값 개수 확인
data.info()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1196 entries, 0 to 1195
Data columns (total 11 columns):
 #   Column             Non-Null Count  Dtype 
---  ------             --------------  ----- 
 0   Attrition          1196 non-null   int64 
 1   Age                1196 non-null   int64 
 2   DistanceFromHome   1196 non-null   int64 
 3   EmployeeNumber     1196 non-null   int64 
 4   Gender             1196 non-null   object
 5   JobSatisfaction    1196 non-null   int64 
 6   MaritalStatus      1196 non-null   object
 7   MonthlyIncome      1196 non-null   int64 
 8   OverTime           1196 non-null   object
 9   PercentSalaryHike  1196 non-null   int64 
 10  TotalWorkingYears  1196 non-null   int64 
dtypes: int64(8), object(3)
memory usage: 102.9+ KB
3) 기초통계정보 확인
  • describe() 메소드는 데이터에 대한 많은 정보를 제공하는 매우 중요한 메소드이다.
  • 개수(count), 평균(mean), 표준편차(std), 최솟값(min), 사분위값(25%, 50%, 75%), 최댓값(max)을 표시한다.
1
data.describe()
AttritionAgeDistanceFromHomeEmployeeNumberJobSatisfactionMonthlyIncomePercentSalaryHikeTotalWorkingYears
count1196.0000001196.000001196.0000001196.0000001196.0000001196.0000001196.0000001196.000000
mean0.16304336.943989.2583611035.6295992.7165556520.10451515.25167211.330268
std0.3695609.092708.166016604.3401301.1109624665.9022533.6259467.823821
min0.00000018.000001.0000001.0000001.0000001009.00000011.0000000.000000
25%0.00000030.000002.000000507.7500002.0000002928.25000012.0000006.000000
50%0.00000036.000007.0000001028.0000003.0000004973.50000014.00000010.000000
75%0.00000043.0000014.0000001581.2500004.0000008420.50000018.00000015.000000
max1.00000060.0000029.0000002068.0000004.00000019999.00000025.00000040.000000
  • 일부 열에 대해서만 기초통계정보를 확인할 수 있다.
1
print(data[['Age', 'MonthlyIncome']].describe())
1
2
3
4
5
6
7
8
9
              Age  MonthlyIncome
count  1196.00000    1196.000000
mean     36.94398    6520.104515
std       9.09270    4665.902253
min      18.00000    1009.000000
25%      30.00000    2928.250000
50%      36.00000    4973.500000
75%      43.00000    8420.500000
max      60.00000   19999.000000

[3] 정렬해서 보기

  • 인덱스를 기준으로 정렬하는 방법과 특정 열을 기준으로 정렬하는 방법이 있다.
  • sort_values() 메소드로 특정 열을 기준으로 정렬.
  • ascending 옵션을 설정해 오름차순, 내림차순을 설정할 수 있다.
    • ascending=True: 오름차순 정렬(기본값)
    • ascending=False: 내림차순 정렬
1
data.sort_values(by='MonthlyIncome', ascending=False)
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
2400521259Male3Married19999No1434
23404171035Female3Divorced19973No2221
32205641191Female1Divorced19943No1328
53005011226Female2Single19926No1521
5321552787Male1Married19859Yes1324
....................................
150129241928Male1Single1091No171
111813091876Male4Single1081No131
709028101056Male2Married1052No221
86201851012Male4Single1051No150
9112010701Male3Single1009Yes111

1196 rows × 11 columns

1
2
# 복합 열 정렬
data.sort_values(by=['JobSatisfaction', 'MonthlyIncome'], ascending=[True, False])
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
32205641191Female1Divorced19943No1328
5321552787Male1Married19859Yes1324
27305811423Female1Married19701Yes2132
4180607549Female1Married19566No1133
6850545522Male1Married19406No1124
....................................
19703121974Female4Divorced1129Yes111
386125241273Male4Single1118Yes141
6841192243Male4Single1102No221
111813091876Male4Single1081No131
86201851012Male4Single1051No150

1196 rows × 11 columns

1
2
3
# 복합 열 정렬 : 별도로 저장하고, 인덱스 reset
temp = data.sort_values(by=['JobSatisfaction', 'MonthlyIncome'], ascending=[True, False])
temp.reset_index(drop = True)
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
005641191Female1Divorced19943No1328
11552787Male1Married19859Yes1324
205811423Female1Married19701Yes2132
30607549Female1Married19566No1133
40545522Male1Married19406No1124
....................................
119103121974Female4Divorced1129Yes111
1192125241273Male4Single1118Yes141
11931192243Male4Single1102No221
119413091876Male4Single1081No131
119501851012Male4Single1051No150

1196 rows × 11 columns

[4] 기본 집계

  • 데이터를 좀 더 이해하기 위해 고유값, 합, 평균, 최댓값, 최솟값 등을 확인.
    1) 고유값 확인
  • 범주형 열(열이 가진 값이 일정한 경우, 성별, 등급 등)인지 확인할 때 사용.

고유값 확인

  • unique() 메소드로 고유값을 확인하며, 결과값은 배열 형태
1
2
# MaritalStatus 열 고유값 확인
print(data['MaritalStatus'].unique())
1
['Married' 'Single' 'Divorced']

고유값과 개수 확인

  • value_counts() 메소드로 고유값과 그 개수를 확인하며, 결과값은 시리즈 형태
1
2
# MaritalStatus 열 고유값 개수 확인
print(data['MaritalStatus'].value_counts())
1
2
3
4
Married     548
Single      384
Divorced    264
Name: MaritalStatus, dtype: int64
2) 기본 집계 메소드 사용
  • 데이터를 1차 집계 한 후 분석을 진행하는 경우가 많으므로 필히 알아두어야 하는 내용
  • 이후에 배우는 Groupby 기능에서 같이 사용됨
1
2
# MonthlyIncome 열 합계 조회
print(data['MonthlyIncome'].sum())
1
7798045
1
2
# MonthlyIncome 열 최댓값 조회
print(data['MonthlyIncome'].max())
1
19999
1
2
# 'Age', 'MonthlyIncome' 열 평균값 확인
print(data[['Age', 'MonthlyIncome']].mean())
1
2
3
Age                36.943980
MonthlyIncome    6520.104515
dtype: float64
1
2
# 'Age', 'MonthlyIncome' 열 중앙값 확인
print(data[['Age', 'MonthlyIncome']].median())
1
2
3
Age                36.0
MonthlyIncome    4973.5
dtype: float64

(4) DataFrame 조회

  • 보고자 하는 데이터를 즉시 조회할 수 있도록 반복 학습과 실습을 통해 익숙해져야 함
  • 데이터프레임을 대상으로 조회하는 방법은 다양하다.
  • 그 중 한가지 방법을 선택해 일관되게 사용하기를 권고

[1] 특정 열 조회

  • df.loc[:, [열 이름1, 열 이름2, … ]] 형태로 조회할 열 이름을 리스트로 지정
  • 열부분은 생략할 수 있지만, 행 부분을 생략할 수는 없다.
  • 하지만 df[[열 이름1, 열 이름2, …]] 형태로 인덱서를 생략함이 일반적이다.
  • 조회할 열이 하나면 리스트 형태가 아니어도 된다.
1
2
# Attrition 열 조회 : 시리즈로 조회 (조금 더 권장하는 방법)
data['Attrition']
1
2
3
4
5
6
7
8
9
10
11
12
0       0
1       0
2       0
3       0
4       1
       ..
1191    0
1192    0
1193    0
1194    0
1195    0
Name: Attrition, Length: 1196, dtype: int64
1
2
# Attrition 열 조회2 : 시리즈로 조회 (오류 발생 가능성 있음)
data.Attrition
1
2
3
4
5
6
7
8
9
10
11
12
0       0
1       0
2       0
3       0
4       1
       ..
1191    0
1192    0
1193    0
1194    0
1195    0
Name: Attrition, Length: 1196, dtype: int64
1
2
3
# Attrition, Age 열 조회 : 데이터프레임으로 조회
# 대괄호 안에 리스트!!!
data[['Attrition', 'Age' ]]
AttritionAge
0033
1035
2042
3046
4122
.........
1191032
1192027
1193029
1194029
1195043

1196 rows × 2 columns

[2] 조건으로 조회

  • df.loc[조건] 형태로 조건을 지정해 조건에 만족하는 데이터만 조회할 수 있다.
  • 우선 조건이 제대로 판단이 되는지 확인한 후, 그 조건을 대괄호 안에 넣으면 된다.
1) 단일 조건 조회
1
2
# 조건절(조건문)의 결과는 True, False
data['DistanceFromHome'] > 10
1
2
3
4
5
6
7
8
9
10
11
12
0       False
1        True
2       False
3       False
4       False
        ...  
1191    False
1192     True
1193    False
1194    False
1195     True
Name: DistanceFromHome, Length: 1196, dtype: bool
1
2
# DistanceFromHome 열 값이 10 보다 큰 행 조회
data.loc[data['DistanceFromHome'] > 10]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
1035181412Male4Single9362No1110
5024211551Male1Divorced2296No142
7030201084Male1Married9957No157
1113315582Male3Married13610Yes1215
150342360Male3Single4568No2010
....................................
1181035281596Male3Married3407No1710
1186126201818Female2Married2148Yes116
1188029191497Male3Divorced8620No1410
1192027191619Male1Divorced4066No117
119504316327Female4Married16064Yes2222

363 rows × 11 columns

2) 여러 조건 조회
1
2
# and로 여러 조건 연결
data.loc[(data['DistanceFromHome'] > 10) & (data['JobSatisfaction'] == 4)]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
1035181412Male4Single9362No1110
5002915346Male4Single2340No196
51045281546Male4Married2132No208
64032151955Female4Divorced6667No189
82135121667Male4Single4581Yes2413
....................................
1104034191701Female4Married2929No1210
1126035111137Male4Divorced4968No115
114114911840Female4Married7654No189
1148036181133Male4Single7779No2018
119504316327Female4Married16064Yes2222

107 rows × 11 columns

1
2
# or 조건 : |
data.loc[(data['DistanceFromHome'] > 10) | (data['JobSatisfaction'] == 4)]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
1035181412Male4Single9362No1110
5024211551Male1Divorced2296No142
7030201084Male1Married9957No157
80266686Female4Married2659Yes133
1113315582Male3Married13610Yes1215
....................................
1186126201818Female2Married2148Yes116
1188029191497Male3Divorced8620No1410
11900275844Male4Divorced12808Yes169
1192027191619Male1Divorced4066No117
119504316327Female4Married16064Yes2222

629 rows × 11 columns

3) isin(), between()
  • isin([값1, 값2, ..., 값n]) : 값1 또는 값2 또는 .. 값n 인 데이터만 조회
  • 주의 : isin(리스트) 값들을 리스트 형태로 입력해야 한다.
1
2
# 값 나열
data.loc[data['JobSatisfaction'].isin([1,4])]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
1035181412Male4Single9362No1110
204261911Male1Married13348No1318
304621204Female1Married17048No2328
5024211551Male1Divorced2296No142
7030201084Male1Married9957No157
....................................
118403351395Male4Married9998No138
1185024101746Male4Married2145No143
11900275844Male4Divorced12808Yes169
1192027191619Male1Divorced4066No117
119504316327Female4Married16064Yes2222

616 rows × 11 columns

  • 위 구문은 다음과 같은 의미를 갖는다.
1
2
# or 조건
data.loc[(data['JobSatisfaction'] == 1) | (data['JobSatisfaction'] == 4)]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
1035181412Male4Single9362No1110
204261911Male1Married13348No1318
304621204Female1Married17048No2328
5024211551Male1Divorced2296No142
7030201084Male1Married9957No157
....................................
118403351395Male4Married9998No138
1185024101746Male4Married2145No143
11900275844Male4Divorced12808Yes169
1192027191619Male1Divorced4066No117
119504316327Female4Married16064Yes2222

616 rows × 11 columns

  • between(값1, 값2) : 값1 ~ 값2 까지 범위안의 데이터만 조회
1
2
# 범위 지정
data.loc[data['Age'].between(25, 30)]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
7030201084Male1Married9957No157
80266686Female4Married2659Yes133
160305197Female1Divorced3204No148
2802611893Female3Married2933Yes131
3203071224Male3Divorced3491No1310
....................................
1188029191497Male3Divorced8620No1410
11900275844Male4Divorced12808Yes169
1192027191619Male1Divorced4066No117
119302991558Male3Married2451No185
11940292469Male3Married4649No144

238 rows × 11 columns

  • 위 구문은 다음과 같은 의미를 갖는다.
1
2
# and 조건
data.loc[(data['Age'] >= 25) & (data['Age'] <= 30)]
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
7030201084Male1Married9957No157
80266686Female4Married2659Yes133
160305197Female1Divorced3204No148
2802611893Female3Married2933Yes131
3203071224Male3Divorced3491No1310
....................................
1188029191497Male3Divorced8620No1410
11900275844Male4Divorced12808Yes169
1192027191619Male1Divorced4066No117
119302991558Male3Married2451No185
11940292469Male3Married4649No144

238 rows × 11 columns

4) 조건을 만족하는 행의 일부 열 조회
  • df.loc[조건, ['열 이름1', '열 이름2', ...]] 형태로 조회할 열을 리스트로 지정 => 2차원, 데이터프레임 형태로 조회
1
2
# 조건에 맞는 하나의 열 조회
data.loc[data['MonthlyIncome'] >= 10000, ['Age']]
Age
033
242
346
1133
1339
......
115742
115854
116634
119027
119543

230 rows × 1 columns

1
2
# 조건에 맞는 여러 열 조회
data.loc[data['MonthlyIncome'] >= 10000, ['Age', 'MaritalStatus', 'TotalWorkingYears']]
AgeMaritalStatusTotalWorkingYears
033Married14
242Married18
346Married28
1133Married15
1339Single21
............
115742Single24
115854Married36
116634Single14
119027Divorced9
119543Married22

230 rows × 3 columns

연습문제

  • MaritalStatus 가 Single 이고, 나이가 30~40 인 직원을 월급순으로 정렬 (내림차순)
1
data.loc[(data['MaritalStatus'] == 'Single') & (data['Age'].between(30, 40))].sort_values(['MonthlyIncome'], ascending=False)
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
109204071740Male2Single19833No1421
467040141128Male3Single19626No1421
1303992022Male4Single19431No1321
26503181430Female2Single16422No119
42004091166Female3Single13499No1720
....................................
460363238Male2Single2088No1213
56803671659Male2Single2013No1115
2613221692Male2Single1393No121
30113181433Female2Single1261No121
111813091876Male4Single1081No131

175 rows × 11 columns

5) 기타

(1) loc와 iloc

  • loc는 index 이름, iloc는 index number 기준으로 탐색
1
2
s = pd.Series(np.nan, index=[49,48,47,46,45, 1, 2, 3, 4, 5])
s.loc[:3]
1
2
3
4
5
6
7
8
9
49   NaN
48   NaN
47   NaN
46   NaN
45   NaN
1    NaN
2    NaN
3    NaN
dtype: float64
1
s.iloc[:3]
1
2
3
4
49   NaN
48   NaN
47   NaN
dtype: float64

(2) isnull()

  • column 또는 row 값의 NaN(null) 값의 index를 반환함
1
data.isnull().head()
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
0FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse
1FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse
2FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse
3FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse
4FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse
1
data.isnull().sum()
1
2
3
4
5
6
7
8
9
10
11
12
Attrition            0
Age                  0
DistanceFromHome     0
EmployeeNumber       0
Gender               0
JobSatisfaction      0
MaritalStatus        0
MonthlyIncome        0
OverTime             0
PercentSalaryHike    0
TotalWorkingYears    0
dtype: int64

(3) 기타 메소드

  • df.T : Transpose
  • df.values : 값 출력
  • df.to_csv() : csv 변환
  • del df["debt"] : column 삭제
  • df.cumsum() : 누적 합
  • df.cummax() : 누적 최대
  • df.cummin() : 누적 최소

(5) DataFrame 수정

[1] Index 변경

1
df
first_namelast_nameagecity
0JasonMiller42San Francisco
1MollyJacobson52Baltimore
2TinaAli36Miami
3JakeMilner24Douglas
4AmyCooze73Boston
1
2
df.index = df['first_name']
df
first_namelast_nameagecity
first_name
JasonJasonMiller42San Francisco
MollyMollyJacobson52Baltimore
TinaTinaAli36Miami
JakeJakeMilner24Douglas
AmyAmyCooze73Boston

[2] 열 삭제

1
2
del df['first_name']
df
last_nameagecity
first_name
JasonMiller42San Francisco
MollyJacobson52Baltimore
TinaAli36Miami
JakeMilner24Douglas
AmyCooze73Boston

[3] Index 재설정

1
df.reset_index()
first_namelast_nameagecity
0JasonMiller42San Francisco
1MollyJacobson52Baltimore
2TinaAli36Miami
3JakeMilner24Douglas
4AmyCooze73Boston

[4] Data Drop

1
df.drop('city', axis=1)
last_nameage
first_name
JasonMiller42
MollyJacobson52
TinaAli36
JakeMilner24
AmyCooze73
1
df
last_nameagecity
first_name
JasonMiller42San Francisco
MollyJacobson52Baltimore
TinaAli36Miami
JakeMilner24Douglas
AmyCooze73Boston
1
2
# 여러개 없애기
df.drop(['city', 'age'], axis=1)
last_name
first_name
JasonMiller
MollyJacobson
TinaAli
JakeMilner
AmyCooze

(6) DataFrame 집계

  • 상세 데이터가 아닌 집계된 데이터에 대한 분석을 자주 요구하니 익숙해져야 할 내용임.
  • sum(), mean(), max(), min(), count() 메소드를 사용해 지정한 열 또는 열들을 기준으로 집계한다.

    [1] Groupby

  • df.groupby(['집계기준변수'], as_index=)['집계대상변수'].집계함수
    • 집계기준변수 : ~~별에 해당되는 변수 혹은 리스트. 범주형 변수 (ex: 월 별, 지역 별 등)
    • 집계대상변수 : 집계함수로 집계할 변수 혹은 리스트. (ex: 매출액 합계)
  • as_index = True (Default)
    • 집계기준변수를 인덱스로 사용
1
2
3
4
5
6
# 데이터 읽어오기
path = 'https://raw.githubusercontent.com/DA4BAM/dataset/master/Attrition_simple2.CSV'
data = pd.read_csv(path)  

# 상위 5개 확인
data.head(5)
AttritionAgeDistanceFromHomeEmployeeNumberGenderJobSatisfactionMaritalStatusMonthlyIncomeOverTimePercentSalaryHikeTotalWorkingYears
00337817Male3Married11691No1114
1035181412Male4Single9362No1110
204261911Male1Married13348No1318
304621204Female1Married17048No2328
41224593Male3Single3894No164

1) 열 하나 집계

1
2
# MonthlyIncome 합계
data['MonthlyIncome'].sum()
1
7798045
1
2
# MonthlyIncome, TotalWorkingYears 각각의 평균
data[['MonthlyIncome', 'TotalWorkingYears']].mean()
1
2
3
MonthlyIncome        6520.104515
TotalWorkingYears      11.330268
dtype: float64
1
2
# MaritalStatus 별 Age 평균 --> 시리즈
data.groupby('MaritalStatus', as_index=True)['Age'].mean()
1
2
3
4
5
MaritalStatus
Divorced    37.522727
Married     37.704380
Single      35.460938
Name: Age, dtype: float64
1
2
# MaritalStatus 별 Age 평균 --> 데이터프레임
data.groupby('MaritalStatus', as_index=True)[['Age']].mean()
Age
MaritalStatus
Divorced37.522727
Married37.704380
Single35.460938
1
2
# MaritalStatus 별 Age 평균 --> 데이터프레임
data.groupby('MaritalStatus', as_index=False)[['Age']].mean()
MaritalStatusAge
0Divorced37.522727
1Married37.704380
2Single35.460938
1
2
3
4
data_mean = data.groupby('MaritalStatus', as_index=False)[['Age']].mean()

# 확인
data_mean
MaritalStatusAge
0Divorced37.522727
1Married37.704380
2Single35.460938

2) 여러 열 집계

1
2
3
4
data_mean = data.groupby('MaritalStatus', as_index=False)[['Age','MonthlyIncome']].mean()

# 확인
data_mean
MaritalStatusAgeMonthlyIncome
0Divorced37.5227276707.018939
1Married37.7043806880.144161
2Single35.4609385877.794271
  • sum() 메소드 앞에 아무 열도 지정하지 않으면 기준열 이외의 모든 열에 대한 집계가 수행됩니다.
1
2
3
4
data_sum = data.groupby('MaritalStatus', as_index=False).sum()

# 확인
data_sum
MaritalStatusAttritionAgeDistanceFromHomeEmployeeNumberJobSatisfactionMonthlyIncomePercentSalaryHikeTotalWorkingYears
0Divorced2399062404266305716177065339583106
1Married692066252955844461468377031984316470
2Single1031361733743878621065225707358523975
  • by=[‘feature1’, ‘feature2’] 과 같이 집계 기준 열을 여럿 설정할 수도 있습니다.
1
2
3
4
5
# 'MaritalStatus', 'Gender'별 나머지 열들 평균 조회
data_sum = data.groupby(['MaritalStatus', 'Gender'], as_index=False)[['Age','MonthlyIncome']].mean()

# 확인
data_sum
MaritalStatusGenderAgeMonthlyIncome
0DivorcedFemale37.0105266626.315789
1DivorcedMale37.8106516752.384615
2MarriedFemale38.7741947301.493088
3MarriedMale37.0030216603.912387
4SingleFemale35.2611465963.445860
5SingleMale35.5991195818.555066

[2] Aggregation

  • df.groupby( ).agg([‘함수1’,’함수2’, …])
  • 여러 함수로 한꺼번에 집계
  • as_index 예외 : .agg()를 사용하면 as_index = False 해도, ~~별 칼럼이 인덱스로 들어간다.
1
2
3
data_agg = data.groupby('MaritalStatus', as_index=False)[['MonthlyIncome']].agg(['min','max','mean'])
# 확인
data_agg
MonthlyIncome
minmaxmean
MaritalStatus
Divorced1129199736707.018939
Married1052199996880.144161
Single1009199265877.794271
This post is licensed under CC BY 4.0 by the author.

[KT Aivle 3기 AI] 4일차. (2) Numpy

[KT Aivle 3기 AI] 5일차. (1) DataFrame 변경