머신러닝 스터디 - 판다스(Pandas)

무지성개발·2021년 9월 25일
0

ml

목록 보기
5/9

Prerequisite

판다스에서 사용할 예제 데이터는
캐글(Kaggle)에서 제공하는 타이타닉 탑승자 데이터
https://www.kaggle.com/c/titanic/data

titanic 폴더안에 csv 파일들을 다운받습니다.

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

import pandas as pd

read_csv()
read_csv()를 이용하여 csv 파일을 편리하게 DataFrame으로 로딩합니다.
read_csv() 의 sep 인자를 콤마(,)가 아닌 다른 분리자로 변경하여 다른 유형의 파일도 로드가 가능합니다.

titanic_df = pd.read_csv('titanic_train.csv')
print('titanic 변수 type:',type(titanic_df))
titanic 변수 type: <class 'pandas.core.frame.DataFrame'>

head()
DataFrame의 맨 앞 일부 데이터만 추출합니다.

titanic_df.head(5)
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

DataFrame의 생성

dic1 = {'Name': ['Chulmin', 'Eunkyung','Jinwoong','Soobeom'],
        'Year': [2011, 2016, 2015, 2015],
        'Gender': ['Male', 'Female', 'Male', 'Male']
       }
# 딕셔너리를 DataFrame으로 변환
data_df = pd.DataFrame(dic1)
print(data_df)
print("#"*30)

# 새로운 컬럼명을 추가
data_df = pd.DataFrame(dic1, columns=["Name", "Year", "Gender", "Age"])
print(data_df)
print("#"*30)

# 인덱스를 새로운 값으로 할당. 
data_df = pd.DataFrame(dic1, index=['one','two','three','four'])
print(data_df)
print("#"*30)
   Gender      Name  Year
0    Male   Chulmin  2011
1  Female  Eunkyung  2016
2    Male  Jinwoong  2015
3    Male   Soobeom  2015
##############################
       Name  Year  Gender  Age
0   Chulmin  2011    Male  NaN
1  Eunkyung  2016  Female  NaN
2  Jinwoong  2015    Male  NaN
3   Soobeom  2015    Male  NaN
##############################
       Gender      Name  Year
one      Male   Chulmin  2011
two    Female  Eunkyung  2016
three    Male  Jinwoong  2015
four     Male   Soobeom  2015
##############################

DataFrame의 컬럼명과 인덱스

print("columns:",titanic_df.columns)
print("index:",titanic_df.index)
print("index value:", titanic_df.index.values)
columns: Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
index: RangeIndex(start=0, stop=891, step=1)
index value: [  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]

DataFrame에서 Series 추출 및 DataFrame 필터링 추출

# DataFrame객체에서 []연산자내에 한개의 컬럼만 입력하면 Series 객체를 반환  
series = titanic_df['Name']
print(series.head(3))
print("## type:",type(series))

# DataFrame객체에서 []연산자내에 여러개의 컬럼을 리스트로 입력하면 그 컬럼들로 구성된 DataFrame 반환  
filtered_df = titanic_df[['Name', 'Age']]
print(filtered_df.head(3))
print("## type:", type(filtered_df))

# DataFrame객체에서 []연산자내에 한개의 컬럼을 리스트로 입력하면 한개의 컬럼으로 구성된 DataFrame 반환 
one_col_df = titanic_df[['Name']]
print(one_col_df.head(3))
print("## type:", type(one_col_df))
0                              Braund, Mr. Owen Harris
1    Cumings, Mrs. John Bradley (Florence Briggs Th...
2                               Heikkinen, Miss. Laina
Name: Name, dtype: object
## type: <class 'pandas.core.series.Series'>
                                                Name   Age
0                            Braund, Mr. Owen Harris  22.0
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  38.0
2                             Heikkinen, Miss. Laina  26.0
## type: <class 'pandas.core.frame.DataFrame'>
                                                Name
0                            Braund, Mr. Owen Harris
1  Cumings, Mrs. John Bradley (Florence Briggs Th...
2                             Heikkinen, Miss. Laina
## type: <class 'pandas.core.frame.DataFrame'>

shape
DataFrame의 행(Row)와 열(Column) 크기를 가지고 있는 속성입니다.

print('DataFrame 크기: ', titanic_df.shape)
DataFrame 크기:  (891, 12)

info()
DataFrame내의 컬럼명, 데이터 타입, Null건수, 데이터 건수 정보를 제공합니다.

titanic_df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
PassengerId    891 non-null int64
Survived       891 non-null int64
Pclass         891 non-null int64
Name           891 non-null object
Sex            891 non-null object
Age            714 non-null float64
SibSp          891 non-null int64
Parch          891 non-null int64
Ticket         891 non-null object
Fare           891 non-null float64
Cabin          204 non-null object
Embarked       889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.6+ KB

describe()
데이터값들의 평균,표준편차,4분위 분포도를 제공합니다. 숫자형 컬럼들에 대해서 해당 정보를 제공합니다.

titanic_df.describe()
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

value_counts()
동일한 개별 데이터 값이 몇건이 있는지 정보를 제공합니다. 즉 개별 데이터값의 분포도를 제공합니다.
주의할 점은 value_counts()는 Series객체에서만 호출 될 수 있으므로 반드시 DataFrame을 단일 컬럼으로 입력하여 Series로 변환한 뒤 호출합니다.

value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
3    491
1    216
2    184
Name: Pclass, dtype: int64
titanic_pclass = titanic_df['Pclass']
print(type(titanic_pclass))
<class 'pandas.core.series.Series'>
titanic_pclass.head()
0    3
1    1
2    3
3    1
4    3
Name: Pclass, dtype: int64
value_counts = titanic_df['Pclass'].value_counts()
print(type(value_counts))
print(value_counts)
<class 'pandas.core.series.Series'>
3    491
1    216
2    184
Name: Pclass, dtype: int64

sort_values()
by=정렬컬럼, ascending=True 또는 False로 오름차순/내림차순으로 정렬

titanic_df.sort_values(by='Pclass', ascending=True)

titanic_df[['Name','Age']].sort_values(by='Age')
titanic_df[['Name','Age','Pclass']].sort_values(by=['Pclass','Age'])
Name Age Pclass
305 Allison, Master. Hudson Trevor 0.92 1
297 Allison, Miss. Helen Loraine 2.00 1
445 Dodge, Master. Washington 4.00 1
802 Carter, Master. William Thornton II 11.00 1
435 Carter, Miss. Lucile Polk 14.00 1
689 Madill, Miss. Georgette Alexandra 15.00 1
329 Hippach, Miss. Jean Gertrude 16.00 1
504 Maioni, Miss. Roberta 16.00 1
853 Lines, Miss. Mary Conover 16.00 1
307 Penasco y Castellana, Mrs. Victor de Satode (M... 17.00 1
550 Thayer, Mr. John Borland Jr 17.00 1
781 Dick, Mrs. Albert Adrian (Vera Gillespie) 17.00 1
311 Ryerson, Miss. Emily Borie 18.00 1
505 Penasco y Castellana, Mr. Victor de Satode 18.00 1
585 Taussig, Miss. Ruth 18.00 1
700 Astor, Mrs. John Jacob (Madeleine Talmadge Force) 18.00 1
27 Fortune, Mr. Charles Alexander 19.00 1
136 Newsom, Miss. Helen Monypeny 19.00 1
291 Bishop, Mrs. Dickinson H (Helen Walton) 19.00 1
748 Marvin, Mr. Daniel Warner 19.00 1
887 Graham, Miss. Margaret Edith 19.00 1
102 White, Mr. Richard Frasar 21.00 1
627 Longley, Miss. Gretchen Fiske 21.00 1
742 Ryerson, Miss. Susan Parker "Suzette" 21.00 1
151 Pears, Mrs. Thomas (Edith Wearne) 22.00 1
356 Bowerman, Miss. Elsie Edith 22.00 1
373 Ringhini, Mr. Sante 22.00 1
539 Frolicher, Miss. Hedwig Margaritha 22.00 1
708 Cleaver, Miss. Alice 22.00 1
88 Fortune, Miss. Mabel Helen 23.00 1
... ... ... ...
653 O'Leary, Miss. Hanora "Norah" NaN 3
656 Radeff, Mr. Alexander NaN 3
667 Rommetvedt, Mr. Knud Paust NaN 3
680 Peters, Miss. Katie NaN 3
692 Lam, Mr. Ali NaN 3
697 Mullens, Miss. Katherine "Katie" NaN 3
709 Moubarek, Master. Halim Gonios ("William George") NaN 3
718 McEvoy, Mr. Michael NaN 3
727 Mannion, Miss. Margareth NaN 3
738 Ivanoff, Mr. Kanio NaN 3
739 Nankoff, Mr. Minko NaN 3
760 Garfirth, Mr. John NaN 3
768 Moran, Mr. Daniel J NaN 3
773 Elias, Mr. Dibo NaN 3
776 Tobin, Mr. Roger NaN 3
778 Kilgannon, Mr. Thomas J NaN 3
783 Johnston, Mr. Andrew G NaN 3
790 Keane, Mr. Andrew "Andy" NaN 3
792 Sage, Miss. Stella Anna NaN 3
825 Flynn, Mr. John NaN 3
826 Lam, Mr. Len NaN 3
828 McCormack, Mr. Thomas Joseph NaN 3
832 Saad, Mr. Amin NaN 3
837 Sirota, Mr. Maurice NaN 3
846 Sage, Mr. Douglas Bullen NaN 3
859 Razi, Mr. Raihed NaN 3
863 Sage, Miss. Dorothy Edith "Dolly" NaN 3
868 van Melkebeke, Mr. Philemon NaN 3
878 Laleff, Mr. Kristo NaN 3
888 Johnston, Miss. Catherine Helen "Carrie" NaN 3

891 rows × 3 columns

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

리스트, ndarray에서 DataFrame변환

import numpy as np

col_name1=['col1']
list1 = [1, 2, 3]
array1 = np.array(list1)

print('array1 shape:', array1.shape )
df_list1 = pd.DataFrame(list1, columns=col_name1)
print('1차원 리스트로 만든 DataFrame:\n', df_list1)
df_array1 = pd.DataFrame(array1, columns=col_name1)
print('1차원 ndarray로 만든 DataFrame:\n', df_array1)
array1 shape: (3,)
1차원 리스트로 만든 DataFrame:
    col1
0     1
1     2
2     3
1차원 ndarray로 만든 DataFrame:
    col1
0     1
1     2
2     3
# 3개의 컬럼명이 필요함. 
col_name2=['col1', 'col2', 'col3']

# 2행x3열 형태의 리스트와 ndarray 생성 한 뒤 이를 DataFrame으로 변환. 
list2 = [[1, 2, 3],
         [11, 12, 13]]
array2 = np.array(list2)
print('array2 shape:', array2.shape )
df_list2 = pd.DataFrame(list2, columns=col_name2)
print('2차원 리스트로 만든 DataFrame:\n', df_list2)
df_array1 = pd.DataFrame(array2, columns=col_name2)
print('2차원 ndarray로 만든 DataFrame:\n', df_array1)
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

딕셔너리(dict)에서 DataFrame변환

# Key는 컬럼명으로 매핑, Value는 리스트 형(또는 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

DataFrame을 ndarray로 변환

# DataFrame을 ndarray로 변환
array3 = df_dict.values
print('df_dict.values 타입:', type(array3), 'df_dict.values shape:', array3.shape)
print(array3)

df_dict.values 타입: <class 'numpy.ndarray'> df_dict.values shape: (2, 3)
[[ 1  2  3]
 [11 22 33]]

DataFrame을 리스트와 딕셔너리로 변환

# DataFrame을 리스트로 변환
list3 = df_dict.values.tolist()
print('df_dict.values.tolist() 타입:', type(list3))
print(list3)

# DataFrame을 딕셔너리로 변환
dict3 = df_dict.to_dict('list')
print('\n df_dict.to_dict() 타입:', type(dict3))
print(dict3)
df_dict.values.tolist() 타입: <class 'list'>
[[1, 2, 3], [11, 22, 33]]

 df_dict.to_dict() 타입: <class 'dict'>
{'col1': [1, 11], 'col2': [2, 22], 'col3': [3, 33]}

DataFrame의 컬럼 데이터 셋 Access

DataFrame의 컬럼 데이터 세트 생성과 수정은 [ ] 연산자를 이용해 쉽게 할 수 있습니다.
새로운 컬럼에 값을 할당하려면 DataFrame [ ] 내에 새로운 컬럼명을 입력하고 값을 할당해주기만 하면 됩니다

titanic_df['Age_0']=0
titanic_df.head(3)
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
titanic_df['Age_by_10'] = titanic_df['Age']*10
titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch']+1
titanic_df.head(3)
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

기존 컬럼에 값을 업데이트 하려면 해당 컬럼에 업데이트값을 그대로 지정하면 됩니다.

titanic_df['Age_by_10'] = titanic_df['Age_by_10'] + 100
titanic_df.head(3)
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 데이터 삭제

axis에 따른 삭제

titanic_drop_df = titanic_df.drop('Age_0', axis=1 )
titanic_drop_df.head(3)
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

drop( )메소드의 inplace인자의 기본값은 False 입니다.
이 경우 drop( )호출을 한 DataFrame은 아무런 영향이 없으며 drop( )호출의 결과가 해당 컬럼이 drop 된 DataFrame을 반환합니다.

titanic_df.head(3)
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

여러개의 컬럼들의 삭제는 drop의 인자로 삭제 컬럼들을 리스트로 입력합니다.
inplace=True 일 경우 호출을 한 DataFrame에 drop이 반영됩니다. 이 때 반환값은 None입니다.

drop_result = titanic_df.drop(['Age_0', 'Age_by_10', 'Family_No'], axis=1, inplace=True)
print(' inplace=True 로 drop 후 반환된 값:',drop_result)
titanic_df.head(3)
 inplace=True 로 drop 후 반환된 값: None
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

axis=0 일 경우 drop()은 row 방향으로 데이터를 삭제합니다.

titanic_df = pd.read_csv('titanic_train.csv')
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 15)
print('#### before axis 0 drop ####')
print(titanic_df.head(6))

titanic_df.drop([0,1,2], axis=0, inplace=True)

print('#### after axis 0 drop ####')
print(titanic_df.head(3))
#### before axis 0 drop ####
   PassengerId  Survived  Pclass            Name     Sex   Age  SibSp  Parch          Ticket     Fare Cabin Embarked
0            1         0       3  Braund, Mr....    male  22.0      1      0       A/5 21171   7.2500   NaN        S
1            2         1       1  Cumings, Mr...  female  38.0      1      0        PC 17599  71.2833   C85        C
2            3         1       3  Heikkinen, ...  female  26.0      0      0  STON/O2. 31...   7.9250   NaN        S
3            4         1       1  Futrelle, M...  female  35.0      1      0          113803  53.1000  C123        S
4            5         0       3  Allen, Mr. ...    male  35.0      0      0          373450   8.0500   NaN        S
5            6         0       3  Moran, Mr. ...    male   NaN      0      0          330877   8.4583   NaN        Q
#### after axis 0 drop ####
   PassengerId  Survived  Pclass            Name     Sex   Age  SibSp  Parch  Ticket     Fare Cabin Embarked
3            4         1       1  Futrelle, M...  female  35.0      1      0  113803  53.1000  C123        S
4            5         0       3  Allen, Mr. ...    male  35.0      0      0  373450   8.0500   NaN        S
5            6         0       3  Moran, Mr. ...    male   NaN      0      0  330877   8.4583   NaN        Q

Index 객체

# 원본 파일 재 로딩 
titanic_df = pd.read_csv('titanic_train.csv')
# Index 객체 추출
indexes = titanic_df.index
print(indexes)
# Index 객체를 실제 값 arrray로 변환 
print('Index 객체 array값:\n',indexes.values)
RangeIndex(start=0, stop=891, step=1)
Index 객체 array값:
 [  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]

Index는 1차원 데이터 입니다.

print(type(indexes.values))
print(indexes.values.shape)
print(indexes[:5].values)
print(indexes.values[:5])
print(indexes[6])
<class 'numpy.ndarray'>
(891,)
[0 1 2 3 4]
[0 1 2 3 4]
6

[ ]를 이용하여 임의로 Index의 값을 변경할 수는 없습니다.

indexes[0] = 5
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-29-2fe1c3d18d1a> in <module>()
----> 1 indexes[0] = 5


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
   1722 
   1723     def __setitem__(self, key, value):
-> 1724         raise TypeError("Index does not support mutable operations")
   1725 
   1726     def __getitem__(self, key):


TypeError: Index does not support mutable operations

Series 객체는 Index 객체를 포함하지만 Series 객체에 연산 함수를 적용할 때 Index는 연산에서 제외됩니다. Index는 오직 식별용으로만 사용됩니다.

series_fair = titanic_df['Fare']
series_fair.head(5)
0     7.2500
1    71.2833
2     7.9250
3    53.1000
4     8.0500
Name: Fare, dtype: float64
print('Fair Series max 값:', series_fair.max())
print('Fair Series sum 값:', series_fair.sum())
print('sum() Fair Series:', sum(series_fair))
print('Fair Series + 3:\n',(series_fair + 3).head(3) )
Fair Series max 값: 512.3292
Fair Series sum 값: 28693.9493
sum() Fair Series: 28693.949299999967
Fair Series + 3:
 0    10.2500
1    74.2833
2    10.9250
Name: Fare, dtype: float64

DataFrame 및 Series에 reset_index( ) 메서드를 수행하면 새롭게 인덱스를 연속 숫자 형으로 할당하며 기존 인덱스는 ‘index’라는 새로운 컬럼 명으로 추가합니다

titanic_reset_df = titanic_df.reset_index(inplace=False)
titanic_reset_df.head(3)
index PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 0 1 0 3 Braund, Mr.... male 22.0 1 0 A/5 21171 7.2500 NaN S
1 1 2 1 1 Cumings, Mr... female 38.0 1 0 PC 17599 71.2833 C85 C
2 2 3 1 3 Heikkinen, ... female 26.0 0 0 STON/O2. 31... 7.9250 NaN S
titanic_reset_df.shape
(891, 13)
print('### before reset_index ###')
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
print('value_counts 객체 변수 타입:',type(value_counts))

new_value_counts = value_counts.reset_index(inplace=False)
print('### After reset_index ###')
print(new_value_counts)
print('new_value_counts 객체 변수 타입:',type(new_value_counts))
### before reset_index ###
3    491
1    216
2    184
Name: Pclass, dtype: int64
value_counts 객체 변수 타입: <class 'pandas.core.series.Series'>
### After reset_index ###
   index  Pclass
0      3     491
1      1     216
2      2     184
new_value_counts 객체 변수 타입: <class 'pandas.core.frame.DataFrame'>

데이터 Selection 및 Filtering

DataFrame의 [ ] 연산자

넘파이에서 [ ] 연산자는 행의 위치, 열의 위치, 슬라이싱 범위 등을 지정해 데이터를 가져올 수 있었습니다.
하지만 DataFrame 바로 뒤에 있는 ‘[ ]’ 안에 들어갈 수 있는 것은 컬럼 명 문자(또는 컬럼 명의 리스트
객체), 또는 인덱스로 변환 가능한 표현식입니다.

titanic_df = pd.read_csv('titanic_train.csv')
print('단일 컬럼 데이터 추출:\n', titanic_df[ 'Pclass' ].head(3))
print('\n여러 컬럼들의 데이터 추출:\n', titanic_df[ ['Survived', 'Pclass'] ].head(3))
print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0])
단일 컬럼 데이터 추출:
 0    3
1    1
2    3
Name: Pclass, dtype: int64

여러 컬럼들의 데이터 추출:
    Survived  Pclass
0         0       3
1         1       1
2         1       3



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2524             try:
-> 2525                 return self._engine.get_loc(key)
   2526             except KeyError:


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


KeyError: 0


During handling of the above exception, another exception occurred:


KeyError                                  Traceback (most recent call last)

<ipython-input-35-a6c18bd06516> in <module>()
      2 print('단일 컬럼 데이터 추출:\n', titanic_df[ 'Pclass' ].head(3))
      3 print('\n여러 컬럼들의 데이터 추출:\n', titanic_df[ ['Survived', 'Pclass'] ].head(3))
----> 4 print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0])


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2137             return self._getitem_multilevel(key)
   2138         else:
-> 2139             return self._getitem_column(key)
   2140 
   2141     def _getitem_column(self, key):


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
   2144         # get column
   2145         if self.columns.is_unique:
-> 2146             return self._get_item_cache(key)
   2147 
   2148         # duplicate columns & possible reduce dimensionality


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   1840         res = cache.get(item)
   1841         if res is None:
-> 1842             values = self._data.get(item)
   1843             res = self._box_item_values(item, values)
   1844             cache[item] = res


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath)
   3841 
   3842             if not isna(item):
-> 3843                 loc = self.items.get_loc(item)
   3844             else:
   3845                 indexer = np.arange(len(self.items))[isna(self.items)]


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2525                 return self._engine.get_loc(key)
   2526             except KeyError:
-> 2527                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2528 
   2529         indexer = self.get_indexer([key], method=method, tolerance=tolerance)


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


KeyError: 0

앞에서 DataFrame의 [ ] 내에 숫자 값을 입력할 경우 오류가 발생한다고 했는데, Pandas의 Index 형태로 변환가능한
표현식은 [ ] 내에 입력할 수 있습니다.
가령 titanic_df의 처음 2개 데이터를 추출하고자 titanic_df [ 0:2 ] 와 같은 슬라이싱을 이용하였다면 정확히 원하는 결과를 반환해 줍니다.

titanic_df[0:2]
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr.... male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mr... female 38.0 1 0 PC 17599 71.2833 C85 C

[ ] 내에 조건식을 입력하여 불린 인덱싱을 수행할 수 있습니다(DataFrame 바로 뒤에 있는 []안에 들어갈 수 있는 것은 컬럼명과 불린인덱싱으로 범위를 좁혀서 코딩을 하는게 도움이 됩니다)

titanic_df[ titanic_df['Pclass'] == 3].head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr.... male 22.0 1 0 A/5 21171 7.250 NaN S
2 3 1 3 Heikkinen, ... female 26.0 0 0 STON/O2. 31... 7.925 NaN S
4 5 0 3 Allen, Mr. ... male 35.0 0 0 373450 8.050 NaN S

DataFrame ix[] 연산자
명칭 기반과 위치 기반 인덱싱 모두를 제공.

titanic_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr.... male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mr... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, ... female 26.0 0 0 STON/O2. 31... 7.9250 NaN S
print('컬럼 위치 기반 인덱싱 데이터 추출:',titanic_df.ix[0,2])
print('컬럼명 기반 인덱싱 데이터 추출:',titanic_df.ix[0,'Pclass'])
컬럼 위치 기반 인덱싱 데이터 추출: 3
컬럼명 기반 인덱싱 데이터 추출: 3


C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
  """Entry point for launching an IPython kernel.
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
Gender Name Year
one Male Chulmin 2011
two Female Eunkyung 2016
three Male Jinwoong 2015
four Male Soobeom 2015
print("\n ix[0,0]", data_df.ix[0,0])
print("\n ix['one', 0]", data_df.ix['one',0])
print("\n ix[3, 'Name']",data_df.ix[3, 'Name'],"\n")

print("\n ix[0:2, [0,1]]\n", data_df.ix[0:2, [0,1]])
print("\n ix[0:2, [0:3]]\n", data_df.ix[0:2, 0:3])
print("\n ix[0:3, ['Name', 'Year']]\n", data_df.ix[0:3, ['Name', 'Year']], "\n")
print("\n ix[:] \n", data_df.ix[:])
print("\n ix[:, :] \n", data_df.ix[:, :])

print("\n ix[data_df.Year >= 2014] \n", data_df.ix[data_df.Year >= 2014])
 ix[0,0] Male

 ix['one', 0] Male

 ix[3, 'Name'] Soobeom 


 ix[0:2, [0,1]]
      Gender      Name
one    Male   Chulmin
two  Female  Eunkyung

 ix[0:2, [0:3]]
      Gender      Name  Year
one    Male   Chulmin  2011
two  Female  Eunkyung  2016

 ix[0:3, ['Name', 'Year']]
            Name  Year
one     Chulmin  2011
two    Eunkyung  2016
three  Jinwoong  2015 


 ix[:] 
        Gender      Name  Year
one      Male   Chulmin  2011
two    Female  Eunkyung  2016
three    Male  Jinwoong  2015
four     Male   Soobeom  2015

 ix[:, :] 
        Gender      Name  Year
one      Male   Chulmin  2011
two    Female  Eunkyung  2016
three    Male  Jinwoong  2015
four     Male   Soobeom  2015

 ix[data_df.Year >= 2014] 
        Gender      Name  Year
two    Female  Eunkyung  2016
three    Male  Jinwoong  2015
four     Male   Soobeom  2015


C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
  """Entry point for launching an IPython kernel.
# data_df 를 reset_index() 로 새로운 숫자형 인덱스를 생성
data_df_reset = data_df.reset_index()
data_df_reset = data_df_reset.rename(columns={'index':'old_index'})

# index 값에 1을 더해서 1부터 시작하는 새로운 index값 생성
data_df_reset.index = data_df_reset.index+1
data_df_reset
old_index Gender Name Year
1 one Male Chulmin 2011
2 two Female Eunkyung 2016
3 three Male Jinwoong 2015
4 four Male Soobeom 2015
# 아래 코드는 오류를 발생합니다. 
data_df_reset.ix[0,1]
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
  



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2524             try:
-> 2525                 return self._engine.get_loc(key)
   2526             except KeyError:


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()


KeyError: 0


During handling of the above exception, another exception occurred:


KeyError                                  Traceback (most recent call last)

<ipython-input-43-3ba6f9b5f35d> in <module>()
      1 # 아래 코드는 오류를 발생합니다.
----> 2 data_df_reset.ix[0,1]


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    119                 pass
    120 
--> 121             return self._getitem_tuple(key)
    122         else:
    123             # we by definition only have the 0th axis


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
    856     def _getitem_tuple(self, tup):
    857         try:
--> 858             return self._getitem_lowerdim(tup)
    859         except IndexingError:
    860             pass


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
    989         for i, key in enumerate(tup):
    990             if is_label_like(key) or isinstance(key, tuple):
--> 991                 section = self._getitem_axis(key, axis=i)
    992 
    993                 # we have yielded a scalar ?


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1106                     return self._get_loc(key, axis=axis)
   1107 
-> 1108             return self._get_label(key, axis=axis)
   1109 
   1110     def _getitem_iterable(self, key, axis=None):


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
    143             raise IndexingError('no slices here, handle elsewhere')
    144 
--> 145         return self.obj._xs(label, axis=axis)
    146 
    147     def _get_loc(self, key, axis=None):


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   2342                                                       drop_level=drop_level)
   2343         else:
-> 2344             loc = self.index.get_loc(key)
   2345 
   2346             if isinstance(loc, np.ndarray):


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2525                 return self._engine.get_loc(key)
   2526             except KeyError:
-> 2527                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2528 
   2529         indexer = self.get_indexer([key], method=method, tolerance=tolerance)


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()


KeyError: 0
data_df_reset.ix[1,1]
'Male'

DataFrame iloc[ ] 연산자
위치기반 인덱싱을 제공합니다.

data_df.head()
Gender Name Year
one Male Chulmin 2011
two Female Eunkyung 2016
three Male Jinwoong 2015
four Male Soobeom 2015
data_df.iloc[0, 0]
'Male'
# 아래 코드는 오류를 발생합니다. 
data_df.iloc[0, 'Name']
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-47-ab5240d8ed9d> in <module>()
      1 # 아래 코드는 오류를 발생합니다.
----> 2 data_df.iloc[0, 'Name']


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1365             except (KeyError, IndexError):
   1366                 pass
-> 1367             return self._getitem_tuple(key)
   1368         else:
   1369             # we by definition only have the 0th axis


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   1735     def _getitem_tuple(self, tup):
   1736 
-> 1737         self._has_valid_tuple(tup)
   1738         try:
   1739             return self._getitem_lowerdim(tup)


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    205                 raise ValueError("Location based indexing can only have "
    206                                  "[{types}] types"
--> 207                                  .format(types=self._valid_types))
    208 
    209     def _should_validate_iterable(self, axis=None):


ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
# 아래 코드는 오류를 발생합니다. 
data_df.iloc['one', 0]
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-48-0fe0a94ee06c> in <module>()
      1 # 아래 코드는 오류를 발생합니다.
----> 2 data_df.iloc['one', 0]


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1365             except (KeyError, IndexError):
   1366                 pass
-> 1367             return self._getitem_tuple(key)
   1368         else:
   1369             # we by definition only have the 0th axis


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   1735     def _getitem_tuple(self, tup):
   1736 
-> 1737         self._has_valid_tuple(tup)
   1738         try:
   1739             return self._getitem_lowerdim(tup)


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
    205                 raise ValueError("Location based indexing can only have "
    206                                  "[{types}] types"
--> 207                                  .format(types=self._valid_types))
    208 
    209     def _should_validate_iterable(self, axis=None):


ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
data_df_reset.head()
old_index Gender Name Year
1 one Male Chulmin 2011
2 two Female Eunkyung 2016
3 three Male Jinwoong 2015
4 four Male Soobeom 2015
data_df_reset.iloc[0, 1]
'Male'

DataFrame loc[ ] 연산자
명칭기반 인덱싱을 제공합니다.

data_df
Gender Name Year
one Male Chulmin 2011
two Female Eunkyung 2016
three Male Jinwoong 2015
four Male Soobeom 2015
data_df.loc['one', 'Name']
'Chulmin'
data_df_reset.loc[1, 'Name']
'Chulmin'
# 아래 코드는 오류를 발생합니다. 
data_df_reset.loc[0, 'Name']
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_type(self, key, axis)
   1505                 if not ax.contains(key):
-> 1506                     error()
   1507             except TypeError as e:


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in error()
   1500                                .format(key=key,
-> 1501                                        axis=self.obj._get_axis_name(axis)))
   1502 


KeyError: 'the label [0] is not in the [index]'


During handling of the above exception, another exception occurred:


KeyError                                  Traceback (most recent call last)

<ipython-input-54-5fc7023ea88b> in <module>()
      1 # 아래 코드는 오류를 발생합니다.
----> 2 data_df_reset.loc[0, 'Name']


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1365             except (KeyError, IndexError):
   1366                 pass
-> 1367             return self._getitem_tuple(key)
   1368         else:
   1369             # we by definition only have the 0th axis


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
    856     def _getitem_tuple(self, tup):
    857         try:
--> 858             return self._getitem_lowerdim(tup)
    859         except IndexingError:
    860             pass


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
    989         for i, key in enumerate(tup):
    990             if is_label_like(key) or isinstance(key, tuple):
--> 991                 section = self._getitem_axis(key, axis=i)
    992 
    993                 # we have yielded a scalar ?


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1624 
   1625         # fall thru to straight lookup
-> 1626         self._has_valid_type(key, axis)
   1627         return self._get_label(key, axis=axis)
   1628 


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_type(self, key, axis)
   1512                 raise
   1513             except:
-> 1514                 error()
   1515 
   1516         return True


C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in error()
   1499                 raise KeyError(u"the label [{key}] is not in the [{axis}]"
   1500                                .format(key=key,
-> 1501                                        axis=self.obj._get_axis_name(axis)))
   1502 
   1503             try:


KeyError: 'the label [0] is not in the [index]'
print('명칭기반 ix slicing\n', data_df.ix['one':'two', 'Name'],'\n')
print('위치기반 iloc slicing\n', data_df.iloc[0:1, 0],'\n')
print('명칭기반 loc slicing\n', data_df.loc['one':'two', 'Name'])
명칭기반 ix slicing
 one     Chulmin
two    Eunkyung
Name: Name, dtype: object 

위치기반 iloc slicing
 one    Male
Name: Gender, dtype: object 

명칭기반 loc slicing
 one     Chulmin
two    Eunkyung
Name: Name, dtype: object
print(data_df_reset.loc[1:2 , 'Name'])
1     Chulmin
2    Eunkyung
Name: Name, dtype: object
print(data_df.ix[1:2 , 'Name'])
two    Eunkyung
Name: Name, dtype: object

불린 인덱싱(Boolean indexing)
헷갈리는 위치기반, 명칭기반 인덱싱을 사용할 필요없이 조건식을 [ ] 안에 기입하여 간편하게 필터링을 수행.

titanic_df = pd.read_csv('titanic_train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60]
print(type(titanic_boolean))
titanic_boolean
titanic_df['Age'] > 60

var1 = titanic_df['Age'] > 60
print(type(var1))
titanic_df[titanic_df['Age'] > 60][['Name','Age']].head(3)
titanic_df[['Name','Age']][titanic_df['Age'] > 60].head(3)
titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(3)

논리 연산자로 결합된 조건식도 불린 인덱싱으로 적용 가능합니다.

titanic_df[ (titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')]

조건식은 변수로도 할당 가능합니다. 복잡한 조건식은 변수로 할당하여 가득성을 향상 할 수 있습니다.

cond1 = titanic_df['Age'] > 60
cond2 = titanic_df['Pclass']==1
cond3 = titanic_df['Sex']=='female'
titanic_df[ cond1 & cond2 & cond3]
import pandas as pd
titanic_df = pd.read_csv('titanic_train.csv')

Aggregation 함수 및 GroupBy 적용

Aggregation 함수

## NaN 값은 count에서 제외
titanic_df.count()

특정 컬럼들로 Aggregation 함수 수행.

titanic_df[['Age', 'Fare']].mean(axis=1)
titanic_df[['Age', 'Fare']].sum(axis=0)
titanic_df[['Age', 'Fare']].count()

groupby( )
by 인자에 Group By 하고자 하는 컬럼을 입력, 여러개의 컬럼으로 Group by 하고자 하면 [ ] 내에 해당 컬럼명을 입력. DataFrame에 groupby( )를 호출하면 DataFrameGroupBy 객체를 반환.

titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby)) 
print(titanic_groupby)
DataFrameGroupBy객체에 Aggregation함수를 호출하여 Group by 수행.
titanic_groupby = titanic_df.groupby('Pclass').count()
titanic_groupby
print(type(titanic_groupby))
print(titanic_groupby.shape)
print(titanic_groupby.index)
titanic_groupby = titanic_df.groupby(by='Pclass')[['PassengerId', 'Survived']].count()
titanic_groupby
titanic_df[['Pclass','PassengerId', 'Survived']].groupby('Pclass').count()
titanic_df.groupby('Pclass')['Pclass'].count()
titanic_df['Pclass'].value_counts()

RDBMS의 group by는 select 절에 여러개의 aggregation 함수를 적용할 수 있음.

Select max(Age), min(Age) from titanic_table group by Pclass

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

titanic_df.groupby('Pclass')['Age'].agg([max, min])

딕셔너리를 이용하여 다양한 aggregation 함수를 적용

agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'}
titanic_df.groupby('Pclass').agg(agg_format)

Missing 데이터 처리하기

DataFrame의 isna( ) 메소드는 모든 컬럼값들이 NaN인지 True/False값을 반환합니다(NaN이면 True)

titanic_df.isna().head(3)

아래와 같이 isna( ) 반환 결과에 sum( )을 호출하여 컬럼별로 NaN 건수를 구할 수 있습니다.

titanic_df.isna( ).sum( )

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

titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')
titanic_df.head(3)
titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()

apply lambda 식으로 데이터 가공

파이썬 lambda 식 기본

def get_square(a):
    return a**2

print('3의 제곱은:',get_square(3))
3의 제곱은: 9
lambda_square = lambda x : x ** 2
print('3의 제곱은:',lambda_square(3))
3의 제곱은: 9
a=[1,2,3]
squares = map(lambda x : x**2, a)
list(squares)
[1, 4, 9]

판다스에 apply lambda 식 적용

titanic_df['Name_len']= titanic_df['Name'].apply(lambda x : len(x))
titanic_df[['Name','Name_len']].head(3)
Name Name_len
0 Braund, Mr. Owen Harris 23
1 Cumings, Mrs. John Bradley (Florence Briggs Th... 51
2 Heikkinen, Miss. Laina 22
titanic_df['Child_Adult'] = titanic_df['Age'].apply(lambda x : 'Child' if x <=15 else 'Adult' )
titanic_df[['Age','Child_Adult']].head(10)
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
8 27.000000 Adult
9 14.000000 Child
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()
Adult      786
Child       83
Elderly     22
Name: Age_cat, dtype: int64
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

titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x))
titanic_df[['Age','Age_cat']].head()
    
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
profile
DevToTheMoon

0개의 댓글