Pandas 시작- 파일을 DataFrame 로딩, 기본 API

  • 넘파이가 다차원이라면 판다스는 2차원 전문
  • 행과 열로 이루어진 2차원 데이터를 효율적으로 가공/처리할 수 있는 기능 제공
  • 파이썬의 리스트, 넘파이, CSV등 파일을 쉽게 DataFrame으로 변경해 데이터의 가공/분석을 편리하게 수행
  • 웨스 매키니(Wes McKinney) 월스트리트 금융회사 분석 전문가, 회사에서 사용하는 분석용 데이터 핸들링 툴이 마음에 안들어서 Pandas 개발

Series

  • 칼럼이 하나 뿐인 데이터 구조체

DataFrame

  • 컬럼이 여러 개인 데이터 구조체
  • 여러개의 Series로 구성

Index

  • RDBMS의 PK 처럼 개별 데이터를 고유하게 식별하는 Key 값
  • Series, DataFrame은 모두 Index를 key 값으로 가짐
In [2]:
# pip install pandas
Collecting pandas
  Downloading pandas-1.0.5-cp38-cp38-win_amd64.whl (8.9 MB)
Collecting pytz>=2017.2
  Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB)
Requirement already satisfied: python-dateutil>=2.6.1 in c:\users\205\.conda\envs\r_study\lib\site-packages (from pandas) (2.8.1)
Requirement already satisfied: numpy>=1.13.3 in c:\users\205\.conda\envs\r_study\lib\site-packages (from pandas) (1.19.0)
Requirement already satisfied: six>=1.5 in c:\users\205\.conda\envs\r_study\lib\site-packages (from python-dateutil>=2.6.1->pandas) (1.15.0)
Installing collected packages: pytz, pandas
Successfully installed pandas-1.0.5 pytz-2020.1
Note: you may need to restart the kernel to use updated packages.
In [1]:
import pandas as pd

kaggle에서 titanic-train.csv 데이터 파일 다운로드

  • 주피터 파일폴더에 다운로드 image.png

image.png

In [2]:
# tab 으로 구분된 파일은 read.table() 사용
# 첫 줄 header=T 디폴트    
titanic_df = pd.read_csv('titanic_train.csv')
In [3]:
print('titanic 변수 type:',type(titanic_df))
titanic_df
titanic 변수 type: <class 'pandas.core.frame.DataFrame'>
Out[3]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
... ... ... ... ... ... ... ... ... ... ... ... ...
886 887 0 2 Montvila, Rev. Juozas male 27.0 0 0 211536 13.0000 NaN S
887 888 1 1 Graham, Miss. Margaret Edith female 19.0 0 0 112053 30.0000 B42 S
888 889 0 3 Johnston, Miss. Catherine Helen "Carrie" female NaN 1 2 W./C. 6607 23.4500 NaN S
889 890 1 1 Behr, Mr. Karl Howell male 26.0 0 0 111369 30.0000 C148 C
890 891 0 3 Dooley, Mr. Patrick male 32.0 0 0 370376 7.7500 NaN Q

891 rows × 12 columns

In [4]:
# .head(원하는 갯수)
titanic_df.head()
Out[4]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
In [5]:
# .shape()
titanic_df.shape
# 12개의 변수 891개의 데이터
Out[5]:
(891, 12)
In [6]:
# .info() - R에서의 str() 같은 역할
# 상세 정보조회 : 컬럼타입, Null Data 개수 등
# object : 거의 문자열, Age, Cabin 컬럼에 Null 값이 많이 있음
titanic_df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB
In [7]:
# .describe()
# R의 summary() 같은 함수
# 숫자형의 분포만 보여줌 (object 타입의 칼럼은 제외)
# 데이터의 분포도는 중요 : 회귀분석에서 결정 값이 정규분포를 따르지 않는 다던가 이상치가 많으면 예측치가 저하됨
# 카테고리 칼럼(Survived 0,1 : Pclass 1,2,3)도 확인 가능(R의 Facter형)

titanic_df.describe()
Out[7]:
PassengerId Survived Pclass Age SibSp Parch Fare
count 891.000000 891.000000 891.000000 714.000000 891.000000 891.000000 891.000000
mean 446.000000 0.383838 2.308642 29.699118 0.523008 0.381594 32.204208
std 257.353842 0.486592 0.836071 14.526497 1.102743 0.806057 49.693429
min 1.000000 0.000000 1.000000 0.420000 0.000000 0.000000 0.000000
25% 223.500000 0.000000 2.000000 20.125000 0.000000 0.000000 7.910400
50% 446.000000 0.000000 3.000000 28.000000 0.000000 0.000000 14.454200
75% 668.500000 1.000000 3.000000 38.000000 1.000000 0.000000 31.000000
max 891.000000 1.000000 3.000000 80.000000 8.000000 6.000000 512.329200
In [8]:
# .value_counts() : Sereis의 유형별 건수 확인, R의 table()
# R에서의 table()과 같은 역할
# DataFrame[컬럼명] : Series 형태로 특정 칼럼 데이터 세트를 반환

value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
3    491
1    216
2    184
Name: Pclass, dtype: int64
In [9]:
# type 확인
# 변수 하나만 가져오면 타입은 시리즈가 됨 ->시리즈는 R의 데이터테이블과 같음
titanic_pclass = titanic_df['Pclass']
print(type(titanic_pclass))
<class 'pandas.core.series.Series'>
In [10]:
# Series - Index : value
titanic_pclass.head()
# 왼쪽 숫자를 인덱스라 함. key값이기 때문에 변하지 않음

# titanic_pclass.tail()
Out[10]:
0    3
1    1
2    3
3    1
4    3
Name: Pclass, dtype: int64
In [11]:
value_counts = titanic_df['Pclass'].value_counts()
print(type(value_counts)) # 시리즈가 리턴됨

print('-----------------------------')
print(value_counts) # 3 1 2 가 index
<class 'pandas.core.series.Series'>
-----------------------------
3    491
1    216
2    184
Name: Pclass, dtype: int64

DataFrame과 리스트, 딕셔너리, 넘파이 ndarray 상호 변환

  • 넘파이 ndarray, 리스트, 딕셔너리를 DataFrame으로 변환하기
In [12]:
# pip install numpy

  • 사이킷런의 많은 API는 DataFrame 인자 사용, 기본은 ndarray 사용, pd 와 nd 상호 간 변환이 매우 빈번하게 발생
  • Pandas는 컬럼명을 가지고 있어 다루기 더 편함
  • 칼럼명을 지정하지 않으면 자동으로 칼럼명 할당
  • columns 속성에 list 값으로 생성 가능
In [13]:
import numpy as np
In [14]:
# 1차원 컬림 1개 필요
col_name1 = ['col1']
list1 = [1, 2, 3]
array1 = np.array(list1)

print('array1 shape:', array1.shape )
array1 shape: (3,)
In [15]:
df_list1 = pd.DataFrame(list1, columns=col_name1)
print('1차원 리스트로 만든 DataFrame:\n', df_list1)
1차원 리스트로 만든 DataFrame:
    col1
0     1
1     2
2     3
In [16]:
df_array1 = pd.DataFrame(array1, columns=col_name1)
print('1차원 ndarray로 만든 DataFrame:\n', df_array1)
1차원 ndarray로 만든 DataFrame:
    col1
0     1
1     2
2     3
In [17]:
# 2차원: 2 x 3 / 3개의 컬럼명이 필요함. 
col_name2=['col1', 'col2', 'col3']
In [18]:
# 2행x3열 형태의 리스트와 ndarray 생성 한 뒤 이를 DataFrame으로 변환. 
list2 = [[1, 2, 3],
         [11, 12, 13]]

array2 = np.array(list2)

print('array2 shape:', array2.shape )
print('-----------------------------')

df_list2 = pd.DataFrame(list2, columns=col_name2)
print('2차원 리스트로 만든 DataFrame:\n', df_list2)
print('-----------------------------')

df_array2 = pd.DataFrame(array2, columns=col_name2)
print('2차원 ndarray로 만든 DataFrame:\n', df_array2)
array2 shape: (2, 3)
-----------------------------
2차원 리스트로 만든 DataFrame:
    col1  col2  col3
0     1     2     3
1    11    12    13
-----------------------------
2차원 ndarray로 만든 DataFrame:
    col1  col2  col3
0     1     2     3
1    11    12    13
In [19]:
# dict 형은 Key는 컬럼명으로 매핑, Value는 리스트 형(또는 ndarray)
# dict = {'컬럼명' : [리스트/ndarray]}
dict = {'col1':[1, 11], 'col2':[2, 22], 'col3':[3, 33]}

df_dict = pd.DataFrame(dict)
print('딕셔너리로 만든 DataFrame:\n', df_dict)
딕셔너리로 만든 DataFrame:
    col1  col2  col3
0     1     2     3
1    11    22    33

values 속성

  • DataFrame을 넘파이 ndarray, 리스트, 딕셔너리로 변환하기
In [20]:
# DataFrame 을 list, ndarray 로 변환 - values 속성
array3 = df_dict.values

print(type(array3))
print('-----------')
print(array3.shape)
print('-----------')
print(array3)
<class 'numpy.ndarray'>
-----------
(2, 3)
-----------
[[ 1  2  3]
 [11 22 33]]
In [21]:
# DataFrame을 리스트로 변환 - tolist()
list3 = df_dict.values.tolist()

print(type(list3))
print(list3)
<class 'list'>
[[1, 2, 3], [11, 22, 33]]
In [22]:
# DataFrame을 딕셔너리로 변환 - to_dict()
dict3 = df_dict.to_dict('list')

print(type(dict3))
print(dict3)
<class 'dict'>
{'col1': [1, 11], 'col2': [2, 22], 'col3': [3, 33]}

DataFrame의 컬럼 데이터 셋 Access

In [23]:
# 새로운 컬럼(Series) 추가, 초기화
titanic_df['Age_0']=0
titanic_df.head(3)
Out[23]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S 0
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C 0
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S 0
In [24]:
# 기존 컬럼 이용하여 새로운 컬럼 생성
titanic_df['Age_by_10'] = titanic_df['Age']*10
titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch'] + 1 
# SibSp : 형제자매, Parch : 부모 자식, +1 은 '나'

titanic_df.head(3)
Out[24]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0 Age_by_10 Family_No
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S 0 220.0 2
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C 0 380.0 2
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S 0 260.0 1
In [25]:
titanic_df['Age_by_10'] = titanic_df['Age_by_10'] + 100
titanic_df.head(3)
Out[25]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0 Age_by_10 Family_No
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S 0 320.0 2
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C 0 480.0 2
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S 0 360.0 1

DataFrame 데이터 삭제

  • drop() 사용
  • axis 0 : 행 방향 / 1 : 열 방향
In [26]:
# 열 삭제
titanic_drop_df = titanic_df.drop('Age_0', axis=1) 
titanic_drop_df.head(3)
Out[26]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_by_10 Family_No
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S 320.0 2
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C 480.0 2
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S 360.0 1
In [27]:
# 원본데이터는 삭제되지 않았음 inplace = False
titanic_df.head(3)
Out[27]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0 Age_by_10 Family_No
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S 0 320.0 2
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C 0 480.0 2
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S 0 360.0 1
In [28]:
# 원본 데이터도 삭제 inplace = True
# 여러 개 삭제 시 리스트 값
drop_result = titanic_df.drop(['Age_0', 'Age_by_10', 'Family_No'], axis=1, inplace=True)

print('inplace=True 로 drop 후 반환된 값:',drop_result) # 반환값 None

titanic_df.head(3)
inplace=True 로 drop 후 반환된 값: None
Out[28]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
In [29]:
print('#### before axis 0 drop ####')
print(titanic_df.head(5))

# 행 삭제
titanic_df.drop([0,1,2], axis=0, inplace=True) 

print('#### after axis 0 drop ####')
print(titanic_df.head(5))
#### before axis 0 drop ####
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   
3            4         1       1   
4            5         0       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0      1   
4                           Allen, Mr. William Henry    male  35.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  
3      0            113803  53.1000  C123        S  
4      0            373450   8.0500   NaN        S  
#### after axis 0 drop ####
   PassengerId  Survived  Pclass  \
3            4         1       1   
4            5         0       3   
5            6         0       3   
6            7         0       1   
7            8         0       3   

                                           Name     Sex   Age  SibSp  Parch  \
3  Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0      1      0   
4                      Allen, Mr. William Henry    male  35.0      0      0   
5                              Moran, Mr. James    male   NaN      0      0   
6                       McCarthy, Mr. Timothy J    male  54.0      0      0   
7                Palsson, Master. Gosta Leonard    male   2.0      3      1   

   Ticket     Fare Cabin Embarked  
3  113803  53.1000  C123        S  
4  373450   8.0500   NaN        S  
5  330877   8.4583   NaN        Q  
6   17463  51.8625   E46        S  
7  349909  21.0750   NaN        S  

Index 객체

  • DataFrame.index, Series.index 로 객체 추출
  • 1차원 ndarray
In [30]:
# 원본 파일 재 로딩 
titanic_df = pd.read_csv('titanic_train.csv')
In [31]:
# Index 객체 추출
indexes = titanic_df.index

print(indexes)
print('--------------------------------------------------------------------------')
print(indexes.values)
# Index 객체를 실제 값 arrray로 변환 
RangeIndex(start=0, stop=891, step=1)
--------------------------------------------------------------------------
[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
 882 883 884 885 886 887 888 889 890]
In [32]:
print(type(indexes.values))
<class 'numpy.ndarray'>
In [33]:
print(indexes.values.shape)
# (891,) : 1차원
(891,)
In [34]:
print(indexes[:5].values)
# 처음~5개까지 슬라이싱
[0 1 2 3 4]
In [35]:
print(indexes.values[:5])
[0 1 2 3 4]
In [36]:
indexes[:5]
Out[36]:
RangeIndex(start=0, stop=5, step=1)
In [37]:
print(indexes[6])
6
In [38]:
# 인덱스 값은 key 값이기때문에 변경 불가. 식별용으로만 사용
indexes[6] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-90644cae6137> in <module>
      1 # 인덱스 값은 key 값이기때문에 변경 불가. 식별용으로만 사용
----> 2 indexes[6] = 1

~\.conda\envs\r_study\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
   3908 
   3909     def __setitem__(self, key, value):
-> 3910         raise TypeError("Index does not support mutable operations")
   3911 
   3912     def __getitem__(self, key):

TypeError: Index does not support mutable operations
In [39]:
series_fair = titanic_df['Fare']
In [40]:
# max
print('Fair Series max 값:', series_fair.max())
Fair Series max 값: 512.3292
In [41]:
# sum
print('Fair Series sum 값:', series_fair.sum())
Fair Series sum 값: 28693.9493
In [42]:
# sum
print('sum() Fair Series:', sum(series_fair))
sum() Fair Series: 28693.949299999967
In [43]:
print('Fair Series + 3:\n',(series_fair + 3).head(3) )
Fair Series + 3:
 0    10.2500
1    74.2833
2    10.9250
Name: Fare, dtype: float64
In [44]:
# reset_index()
# index 새로 만들 때 사용, 연속된 index 아닐때 주로 사용
# 기존 index 삭제 시에는 drop=True 속성 사용
# (default)inplace=False / 원본 훼손하지 않기 위해 (inplace=True 속성을 넣고 실행하면 원본 훼손 됨)

titanic_reset_df = titanic_df.reset_index()
titanic_reset_df.head(3)
Out[44]:
index PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
In [45]:
# value_counts 리셋 전
print('### before reset_index ###')

value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
print('-------------------------------------------------')
print('value_counts 객체 변수 타입:',type(value_counts))
### before reset_index ###
3    491
1    216
2    184
Name: Pclass, dtype: int64
-------------------------------------------------
value_counts 객체 변수 타입: <class 'pandas.core.series.Series'>
In [46]:
# .reset_index 를 통해 value_counts 리셋 후
new_value_counts = value_counts.reset_index()

print('### After reset_index ###')

print(new_value_counts)
print('-------------------------------------------------')
print('new_value_counts 객체 변수 타입:',type(new_value_counts))
### After reset_index ###
   index  Pclass
0      3     491
1      1     216
2      2     184
-------------------------------------------------
new_value_counts 객체 변수 타입: <class 'pandas.core.frame.DataFrame'>

데이터 셀렉션 및 필터링

  • DataFrame의 [ ] 연산자
  • 컬럼 : [컬럼(리스트)] - ['Pclass']
  • 블린인덱스 : [[블린인덱스]] - [['Pclass' == 3]]
  • 슬라이싱연산 : [슬라이싱연산] - [0:3] 비추천
In [47]:
# 단일 컬럼 데이터 추출 (컬럼명이 아니고 숫자를 넣으면 오류남)
titanic_df['Pclass'].head(3)
Out[47]:
0    3
1    1
2    3
Name: Pclass, dtype: int64
In [48]:
# 여러 컬럼 데이터 추출
print(titanic_df[['Survived','Pclass']].head(3))
   Survived  Pclass
0         0       3
1         1       1
2         1       3
In [49]:
# 여러 행 추출
titanic_df[0:2]
Out[49]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
In [50]:
# 열 조건에 맞는 데이터 추출
titanic_df[titanic_df['Pclass'] == 3].head(3)
Out[50]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.250 NaN S
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.925 NaN S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.050 NaN S

Pandas의 특징) index를 여러가지 형태로 넣을 수 있다

In [51]:
data = {'Name': ['Chulmin', 'Eunkyung','Jinwoong','Soobeom'],
        'Year': [2011, 2016, 2015, 2015],
        'Gender': ['Male', 'Female', 'Male', 'Male']
       }
data_df = pd.DataFrame(data, index=['one','two','three','four'])
data_df
Out[51]:
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male

명칭/ 위치 기반 인덱싱

  • 명칭 기반 인덱싱과 위치 기반 인덱싱의 구분
  • 명칭 기반(인덱싱이 문자열로) : 칼럼의 명칭 기반 위치 지정
  • 위치 기반(인덱싱이 숫자로) : 행, 열 기반 위치 지정
In [52]:
# data_df 를 reset_index() 로 새로운 숫자형 인덱스를 생성
data_df_reset = data_df.reset_index()

# rename(columns={ '기존 이름' : '바꿀 이름'}) : 컬럼명 변경
data_df_reset = data_df_reset.rename(columns={'index':'old_index'}) 
data_df_reset
Out[52]:
old_index Name Year Gender
0 one Chulmin 2011 Male
1 two Eunkyung 2016 Female
2 three Jinwoong 2015 Male
3 four Soobeom 2015 Male
In [53]:
# index 값에 1을 더해서 0이 아닌 1부터 시작하는 새로운 index값 생성
data_df_reset.index = data_df_reset.index + 1   
# key값은 각자 바꾸는건 불가능하지만 전체 적용해서 바꾸는 건 가능 (위 코드는 전체에 +1)
    
data_df_reset
Out[53]:
old_index Name Year Gender
1 one Chulmin 2011 Male
2 two Eunkyung 2016 Female
3 three Jinwoong 2015 Male
4 four Soobeom 2015 Male

DateFrame iloc[ ] 연산자 : 순서를 나타내는 정수 기반의 2차원 인덱싱

  • 행,열 기반
  • df.loc[행 인덱싱 값, 열 인덱싱 값]
In [54]:
data_df
Out[54]:
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
In [55]:
data_df.iloc[0,0]  # 컬럼명으로 불러올 수 없음

# 아래 코드는 오류 발생
# data_df.iloc[0, 'Name']
# data_df.iloc['one', 0]
Out[55]:
'Chulmin'

DateFrame loc[ ] 연산자 : 라벨값 기반의 2차원 인덱싱

  • 명칭기반 [index값, 칼럼명]
  • df.loc[행 인덱싱 값]
In [56]:
data_df.loc['one','Name']  # 컬럼명이 아닌 수치를 넣으면 오류

# 아래 코드는 오류
#data_df_reset.loc[0, 'Name']
Out[56]:
'Chulmin'

주의 ) 변경이 가능한 것은 수치 X, 명칭 O !! (index아님)

  • iloc (수치기반) / loc (명칭기반) 를 활용해 값을 가져올 때 주의
In [57]:
data_df_reset
Out[57]:
old_index Name Year Gender
1 one Chulmin 2011 Male
2 two Eunkyung 2016 Female
3 three Jinwoong 2015 Male
4 four Soobeom 2015 Male
In [58]:
# iloc의 경우 (수치기반)

data_df_reset.iloc[1,0]

# 왼쪽에 1,2,3,4는 자동으로 부여된 인덱스가 아닌 내가 설정한 값이므로 수치가 아니라 명칭이다
# 그러므로 iloc[1,0]은 one이 아니라 two
Out[58]:
'two'
In [59]:
# loc의 경우 (명칭기반)

data_df_reset.loc[1,'Name'] 

# loc[1, 'Name']에서의 1은 숫자가 아닌 명칭! 1 인덱스라는 뜻이 아니다!!
Out[59]:
'Chulmin'
In [60]:
# 명칭기반 loc에서는 마지막 값까지 가저옴(명칭 이므로)
data_df_reset.loc[1:2, 'Name']
Out[60]:
1     Chulmin
2    Eunkyung
Name: Name, dtype: object
In [61]:
# 위 데이터와 비교해서 봐두기
data_df.loc['one':'two', 'Name']
Out[61]:
one     Chulmin
two    Eunkyung
Name: Name, dtype: object

Boolean Indexing

  • 불린 인덱싱
  • 편리한 데이터 필터링 방식
  • 조건으로 원하는 값 필터링
  • loc에서 사용
In [62]:
titanic_df = pd.read_csv('titanic_train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60]
print(type(titanic_boolean))
titanic_boolean
<class 'pandas.core.frame.DataFrame'>
Out[62]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
33 34 0 2 Wheadon, Mr. Edward H male 66.0 0 0 C.A. 24579 10.5000 NaN S
54 55 0 1 Ostby, Mr. Engelhart Cornelius male 65.0 0 1 113509 61.9792 B30 C
96 97 0 1 Goldschmidt, Mr. George B male 71.0 0 0 PC 17754 34.6542 A5 C
116 117 0 3 Connors, Mr. Patrick male 70.5 0 0 370369 7.7500 NaN Q
170 171 0 1 Van der hoef, Mr. Wyckoff male 61.0 0 0 111240 33.5000 B19 S
252 253 0 1 Stead, Mr. William Thomas male 62.0 0 0 113514 26.5500 C87 S
275 276 1 1 Andrews, Miss. Kornelia Theodosia female 63.0 1 0 13502 77.9583 D7 S
280 281 0 3 Duane, Mr. Frank male 65.0 0 0 336439 7.7500 NaN Q
326 327 0 3 Nysveen, Mr. Johan Hansen male 61.0 0 0 345364 6.2375 NaN S
438 439 0 1 Fortune, Mr. Mark male 64.0 1 4 19950 263.0000 C23 C25 C27 S
456 457 0 1 Millet, Mr. Francis Davis male 65.0 0 0 13509 26.5500 E38 S
483 484 1 3 Turkula, Mrs. (Hedwig) female 63.0 0 0 4134 9.5875 NaN S
493 494 0 1 Artagaveytia, Mr. Ramon male 71.0 0 0 PC 17609 49.5042 NaN C
545 546 0 1 Nicholson, Mr. Arthur Ernest male 64.0 0 0 693 26.0000 NaN S
555 556 0 1 Wright, Mr. George male 62.0 0 0 113807 26.5500 NaN S
570 571 1 2 Harris, Mr. George male 62.0 0 0 S.W./PP 752 10.5000 NaN S
625 626 0 1 Sutton, Mr. Frederick male 61.0 0 0 36963 32.3208 D50 S
630 631 1 1 Barkworth, Mr. Algernon Henry Wilson male 80.0 0 0 27042 30.0000 A23 S
672 673 0 2 Mitchell, Mr. Henry Michael male 70.0 0 0 C.A. 24580 10.5000 NaN S
745 746 0 1 Crosby, Capt. Edward Gifford male 70.0 1 1 WE/P 5735 71.0000 B22 S
829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) female 62.0 0 0 113572 80.0000 B28 NaN
851 852 0 3 Svensson, Mr. Johan male 74.0 0 0 347060 7.7750 NaN S
In [63]:
# 불린 인덱싱의 리턴값은 DataFrame이므로 원하는 칼럼만 추출 가능
titanic_df[titanic_df['Age'] > 60][['Name', 'Age']].head(3)

# 60세 이상의 이름과 나이만 가져와
Out[63]:
Name Age
33 Wheadon, Mr. Edward H 66.0
54 Ostby, Mr. Engelhart Cornelius 65.0
96 Goldschmidt, Mr. George B 71.0
In [64]:
# loc 활용해서 조건 걸기
titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(3)
Out[64]:
Name Age
33 Wheadon, Mr. Edward H 66.0
54 Ostby, Mr. Engelhart Cornelius 65.0
96 Goldschmidt, Mr. George B 71.0
In [65]:
# 논리연산 가능
# and : & / or : | / not : ~

titanic_df[(titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')]
Out[65]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
275 276 1 1 Andrews, Miss. Kornelia Theodosia female 63.0 1 0 13502 77.9583 D7 S
829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) female 62.0 0 0 113572 80.0000 B28 NaN
In [66]:
cond1 = titanic_df['Age'] > 60
cond2 = titanic_df['Pclass']==1
cond3 = titanic_df['Sex']=='female'
titanic_df[ cond1 & cond2 & cond3]
Out[66]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
275 276 1 1 Andrews, Miss. Kornelia Theodosia female 63.0 1 0 13502 77.9583 D7 S
829 830 1 1 Stone, Mrs. George Nelson (Martha Evelyn) female 62.0 0 0 113572 80.0000 B28 NaN

정렬, Aggregation함수, GroupBy 적용

  • DataFrame, Series의 정렬 - sort_values() : order by
  • ascending=True 오름차순
  • inplace=False DataFrame 유지하면서 정렬된 데이터 리턴
  • inplace=True DataFrame에 정렬된 데이터 적용 됨, None 리턴
In [67]:
titanic_df.head(3)
Out[67]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
In [68]:
# sort_values() : 정렬
titanic_sorted = titanic_df.sort_values(by=['Name'])
titanic_sorted.head(3)
Out[68]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
845 846 0 3 Abbing, Mr. Anthony male 42.0 0 0 C.A. 5547 7.55 NaN S
746 747 0 3 Abbott, Mr. Rossmore Edward male 16.0 1 1 C.A. 2673 20.25 NaN S
279 280 1 3 Abbott, Mrs. Stanton (Rosa Hunt) female 35.0 1 1 C.A. 2673 20.25 NaN S
In [69]:
# ascending = False 옵션으로 내림차순 정렬(default는 True. 오름차순)
titanic_sorted = titanic_df.sort_values(by=['Pclass','Name'], ascending=False)
titanic_sorted.head(3)
Out[69]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
868 869 0 3 van Melkebeke, Mr. Philemon male NaN 0 0 345777 9.5 NaN S
153 154 0 3 van Billiard, Mr. Austin Blyler male 40.5 0 2 A/5. 851 14.5 NaN S
282 283 0 3 de Pelsmaeker, Mr. Alfons male 16.0 0 0 345778 9.5 NaN S

Aggregation 함수()

  • sum(), max(), min(), count() 등의 함수는 DataFrame/Series에서 집합(Aggregation) 연산을 수행
  • DataFrame의 경우 DataFrame에서 바로 aggregation을 호출할 경우 모든 컬럼에 해당 aggregation을 적용
In [72]:
# count() 집계함수
titanic_df.count()
Out[72]:
PassengerId    891
Survived       891
Pclass         891
Name           891
Sex            891
Age            714
SibSp          891
Parch          891
Ticket         891
Fare           891
Cabin          204
Embarked       889
dtype: int64
In [71]:
# mean() 평균함수
titanic_df[['Age', 'Fare']].mean()
Out[71]:
Age     29.699118
Fare    32.204208
dtype: float64

DataFrame Group By() 이용하기

  • DataFrame은 Group by 연산을 위해 groupby() 메소드를 제공
  • groupby() 메소드는 by 인자로 group by 하려는 컬럼명을 입력 받으면 DataFrameGroupBy 객체를 반환
  • 이렇게 반환된 DataFrameGroupBy 객체에 aggregation 함수를 수행
    • 그룹핑을 하면 집계 함수 사용
In [73]:
titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby))
<class 'pandas.core.groupby.generic.DataFrameGroupBy'>
In [74]:
# groupby - count() 적용
titanic_groupby = titanic_df.groupby('Pclass').count()
titanic_groupby
Out[74]:
PassengerId Survived Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
Pclass
1 216 216 216 216 186 216 216 216 216 176 214
2 184 184 184 184 173 184 184 184 184 16 184
3 491 491 491 491 355 491 491 491 491 12 491
In [75]:
# select count('PassengerId'), count('Survived') from titanic_df group by 'Pclass'
titanic_groupby = titanic_df.groupby('Pclass')[['PassengerId', 'Survived']].count()
titanic_groupby
Out[75]:
PassengerId Survived
Pclass
1 216 216
2 184 184
3 491 491

agg() 함수 : 여러개의 aggregation 함수를 적용할 수 있도록 별도로 제공되는 함수

  • 적용 함수가 여러개인 경우 agg([함수명1, 함수명2,...])
In [77]:
# Pclass로 groupby된 Age 컬럼의 max와 min 출력
titanic_df.groupby('Pclass')['Age'].agg([max, min])
Out[77]:
max min
Pclass
1 80.0 0.92
2 70.0 0.67
3 74.0 0.42
In [78]:
# 딕셔너리를 이용해 다양한 aggreagtion 함수 적용
agg_format = {'Age':'max', 'SibSp':'sum', 'Fare':'mean'}
In [79]:
titanic_df.groupby('Pclass').agg(agg_format)

# groupby는 항상 집계함수와 같이 사용
Out[79]:
Age SibSp Fare
Pclass
1 80.0 90 84.154687
2 70.0 74 20.662183
3 74.0 302 13.675550

결손 데이터 처리하기

  • Null 값 / NaN
  • 계산 함수 연산시 자동 제외 됨
  • isna()로 결손 데이터 여부 확인 : 결손 시 True
In [81]:
titanic_df.isna().head(3)
Out[81]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 False False False False False False False False False False True False
1 False False False False False False False False False False False False
2 False False False False False False False False False False True False
In [82]:
# isna()
# True : 1의 합
titanic_df.isna().sum()
Out[82]:
PassengerId      0
Survived         0
Pclass           0
Name             0
Sex              0
Age            177
SibSp            0
Parch            0
Ticket           0
Fare             0
Cabin          687
Embarked         2
dtype: int64

fillna()로 Missing 데이터 대체하기

In [83]:
# 반환받아 다시 넣거나 fillna('값', inplace=True)
titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')
titanic_df.head(3)
Out[83]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 C000 S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 C000 S
In [84]:
# 평균값으로 처리
titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')

titanic_df.isna().sum()
Out[84]:
PassengerId    0
Survived       0
Pclass         0
Name           0
Sex            0
Age            0
SibSp          0
Parch          0
Ticket         0
Fare           0
Cabin          0
Embarked       0
dtype: int64

apply lambda식으로 데이터 가공

  • lambda를 활용해 함수를 간단하게 만들어 사용할 수 있다
  • R의 sapply(), tapply()
  • Python의 map()
In [85]:
def get_square(a):
    return a**2

print('3의 제곱은: ', get_square(3))
3의 제곱은:  9
In [86]:
# 함수명 = lambda 인자 : 리턴값
lambda_square = lambda x : x ** 2

print('3의 제곱은: ', lambda_square(3))
3의 제곱은:  9
In [87]:
# 파이썬의 map함수 활용
# 리스트를 함수에 넣고 돌려서 다시 리스트로 반환
a = [1,2,3]
squares = map(lambda x : x ** 2, a)
list(squares)
Out[87]:
[1, 4, 9]
In [88]:
titanic_df['Name_len'] = titanic_df['Name'].apply(lambda x : len(x))
titanic_df[['Name','Name_len']].head(3) 
# 여러개의 컬럼을 가져오니까 리스트 값을 가져와야 해서 대괄호 두개
Out[88]:
Name Name_len
0 Braund, Mr. Owen Harris 23
1 Cumings, Mrs. John Bradley (Florence Briggs Th... 51
2 Heikkinen, Miss. Laina 22
In [89]:
# if 조건문으로 가져오기
titanic_df['Child_Adult'] = titanic_df['Age'].apply(lambda x : 'Child' if x <= 15 else 'Adult')
titanic_df[['Age', 'Child_Adult']].head(8)
Out[89]:
Age Child_Adult
0 22.000000 Adult
1 38.000000 Adult
2 26.000000 Adult
3 35.000000 Adult
4 35.000000 Adult
5 29.699118 Adult
6 54.000000 Adult
7 2.000000 Child
In [90]:
titanic_df['Age_cat'] = titanic_df['Age'].apply(
    lambda x : 'Child' if x<=15 else('Adult' if x<=60 else 'Elderly'))

titanic_df['Age_cat'].value_counts()
Out[90]:
Adult      786
Child       83
Elderly     22
Name: Age_cat, dtype: int64
In [91]:
# 나이에 따라 세분화딘 분류를 수행하는 함수 생성
# 위 처럼 lambda로 구분하는 것보다 함수를 활용하는게 더 깔끔
def get_category(age):
    cat = ''
    if age <= 5: cat = 'Baby'
    elif age <= 12: cat = 'Child'
    elif age <= 18: cat = 'Teenager'
    elif age <= 25: cat = 'Student'
    elif age <= 35: cat = 'Young Adult'
    elif age <= 60: cat = 'Adult'
    else : cat = 'Elderly'
    
    return cat
In [92]:
# lambda 이용해서 위 함수에서 하나씩 꺼내오기
# lambda 식에 위에서 생성한 get_category( ) 함수를 반환값으로 지정. 
# get_category(X)는 입력값으로 ‘Age’ 컬럼 값을 받아서 해당하는 cat 반환

titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x))
titanic_df[['Age', 'Age_cat']].head()
Out[92]:
Age Age_cat
0 22.0 Student
1 38.0 Adult
2 26.0 Young Adult
3 35.0 Young Adult
4 35.0 Young Adult