데이터 핸들링 - 판다스
Pandas 시작- 파일을 DataFrame 로딩, 기본 API
판다스의 주요 구성 요소
- DataFrame: Column X Rows 2차원 데이터 셋
- Series: 1개의 Column 값으로만 구성된 1차원 데이터 셋
- Index: DataFrame/Series의 고유한 key 값 객체
read_csv()
- read_csv()를 이용하여 csv파일을 편리하게 DataFrame으로 로딩한다.
- read_csv()의 sep인자를 콤마(,)가 아닌 다른 분리자로 변경하여 다른 유형의 파일도 로드가 가능하다.
titanic_df = pd.read_csv('train.csv')
print('titanic 변수 type:',type(titanic_df))
titanic 변수 type: <class 'pandas.core.frame.DataFrame'>
head()와 tail()
- head()는 DataFrame의 맨 앞부터 일부 데이터만 추출한다.
- tail()은 DataFrame의 맨 뒤부터 일부 데이터만 추출한다.
|
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 |
|
PassengerId |
Survived |
Pclass |
Name |
Sex |
Age |
SibSp |
Parch |
Ticket |
Fare |
Cabin |
Embarked |
| 886 |
887 |
0 |
2 |
Montvila, Rev. Juozas |
male |
27.0 |
0 |
0 |
211536 |
13.00 |
NaN |
S |
| 887 |
888 |
1 |
1 |
Graham, Miss. Margaret Edith |
female |
19.0 |
0 |
0 |
112053 |
30.00 |
B42 |
S |
| 888 |
889 |
0 |
3 |
Johnston, Miss. Catherine Helen "Carrie" |
female |
NaN |
1 |
2 |
W./C. 6607 |
23.45 |
NaN |
S |
| 889 |
890 |
1 |
1 |
Behr, Mr. Karl Howell |
male |
26.0 |
0 |
0 |
111369 |
30.00 |
C148 |
C |
| 890 |
891 |
0 |
3 |
Dooley, Mr. Patrick |
male |
32.0 |
0 |
0 |
370376 |
7.75 |
NaN |
Q |
DataFrame 출력 시 option
display(titanic_df.tail(3))
display(titanic_df.head(3))
|
PassengerId |
Survived |
Pclass |
Name |
Sex |
Age |
SibSp |
Parch |
Ticket |
Fare |
Cabin |
Embarked |
| 888 |
889 |
0 |
3 |
Johnston, Miss. Catherine Helen "Carrie" |
female |
NaN |
1 |
2 |
W./C. 6607 |
23.45 |
NaN |
S |
| 889 |
890 |
1 |
1 |
Behr, Mr. Karl Howell |
male |
26.0 |
0 |
0 |
111369 |
30.00 |
C148 |
C |
| 890 |
891 |
0 |
3 |
Dooley, Mr. Patrick |
male |
32.0 |
0 |
0 |
370376 |
7.75 |
NaN |
Q |
|
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 |
pd.set_option('display.max_rows', 1000)
pd.set_option('display.max_colwidth', 100)
pd.set_option('display.max_columns', 100)
titanic_df
-> row가 최대 1000, column의 길이가 최대 100, column이 최대 100까지 출력
(output 생략)
shape
- DataFrame의 행(Row)와 열(Column) 크기를 가지고 있는 속성이다.
print('DataFrame 크기: ', titanic_df.shape)
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)
Name Year Gender
0 Chulmin 2011 Male
1 Eunkyung 2016 Female
2 Jinwoong 2015 Male
3 Soobeom 2015 Male
##############################
Name Year Gender Age
0 Chulmin 2011 Male NaN
1 Eunkyung 2016 Female NaN
2 Jinwoong 2015 Male NaN
3 Soobeom 2015 Male NaN
##############################
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
##############################
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]
-> titanic_df.index.values는 ndarray 형태
info()
- DataFrame내의 컬럼명, 데이터 타입, Null건수, 데이터 건수 정보를 제공한다.
<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
describe()
- 데이터값들의 평균,표준편차,4분위 분포도를 제공한다.
숫자형 컬럼들에 대해서 해당 정보를 제공한다.
|
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객체에서만 호출 될 수 있었지만 현재에는 DataFram에서도 호출가능하다.
- value_counts() 메소드를 사용할 때는 Null 값을 무시하고 결과값을 내놓기 쉽다.
value_counts()는 Null값을 포함하여 개별 데이터 값의 건수를 계산할지 여부를 dropna 인자로 판단한다.
dropna는 디폴트로 True이며 이 경우는 Null값을 무시하고 개별 데이터 값의 건수를 계산한다.
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
Pclass
3 491
1 216
2 184
Name: count, dtype: int64
titanic_df['Pclass'].head()
0 3
1 1
2 3
3 1
4 3
Name: Pclass, dtype: int64
titanic_pclass = titanic_df['Pclass']
print(type(titanic_pclass))
<class 'pandas.core.series.Series'>
print('titanic_df 데이터 건수:', titanic_df.shape[0])
print('기본 설정인 dropna=True로 value_counts()')
# value_counts()는 디폴트로 dropna=True 이므로 value_counts(dropna=True)와 동일.
print(titanic_df['Embarked'].value_counts())
print(titanic_df['Embarked'].value_counts(dropna=False))
titanic_df 데이터 건수: 891
기본 설정인 dropna=True로 value_counts()
Embarked
S 644
C 168
Q 77
Name: count, dtype: int64
Embarked
S 644
C 168
Q 77
NaN 2
Name: count, dtype: int64
# DataFrame에서도 value_counts() 적용 가능.
titanic_df[['Pclass', 'Embarked']].value_counts()
Pclass Embarked
3 S 353
2 S 164
1 S 127
C 85
3 Q 72
C 66
2 C 17
Q 3
1 Q 2
Name: count, dtype: int64
DataFrame과 리스트, 딕셔너리, 넘파이 ndarray 상호 변환
| 변환 형태 |
설명 |
| 리스트(list) -> DataFrame |
df_list1 = pd.DataFrame(list, columns=col_name1) 와 같이 DataFrame 생성 인자로 리스트 객체와 매핑되는 컬럼명들을 입력 |
| ndarray -> DataFrame |
df_array2 = pd.DataFrame(array2, columns=col_name2) 와 같이 DataFrame 생성 인자로 ndarray와 매핑되는 컬럼명들을 입력 |
| 딕셔너리(dict) -> DataFrame |
dict = {‘col1’:[1, 11], ‘col2’:[2, 22], ‘col3’: [3, 33]} df_dict = pd.DataFrame(dict) 와 같이 딕셔너리의 키(key)로 컬럼명을 값(value)을 리스트 형식으로 입력 |
| DataFrame -> ndarray |
DataFrame 객체의 values 속성을 이용하여 ndarray 변환 |
| DataFrame -> 리스트 |
DataFrame 객체의 values 속성을 이용하여 먼저 ndarray로 변환 후 tolist()를 이용하여 list로 변환 |
| DataFrame -> 딕셔너리 |
DataFrame 객체의 to_dict()을 이용하여 변환 |
넘파이 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_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
# 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을 리스트로 변환
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의 칼럼 데이터 세트 생성과 수정
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 Thayer) |
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 Thayer) |
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 Thayer) |
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 데이터 삭제
DataFrame의 drop()
DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
- axis: DataFrame의 row를 삭제할 때는 axis=0, column을 삭제할 때는 axis=1으로 설정
- 원본 DataFrame은 유지하고 드롭된 DataFrame을 새롭게 객체 변수로 받고 싶다면 inplace=False로 설정(default)
예: titanic_df.drop(‘Age_0’, axis=1, inplace=False)
- 원본 DataFrame에 드롭된 결과를 적용할 경우에는 inplace=True를 적용
예: titanic_df.drop(‘Age_0’, axis=1, inplace=True)
- 원본 DataFrame에서 드롭된 DataFrame을 다시 원본 DataFrame 객체 변수로 할당하면 원본 DataFrame에서 드롭된 결과를 적용할 경우와 같음(단, 기존 원본 DataFrame 객체 변수는 메모리에서 추후 제거됨)
예: titanic_df = titanic_df.drop(‘Age_0’, axis=1, inplace=True)
drop()
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 Thayer) |
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 |
|
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 Thayer) |
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 |
-> inplace: False가 default 값이므로 원본 DataFrame은 유지됨
- 여러개의 컬럼들의 삭제는 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 Thayer) |
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 방향으로 데이터를 삭제한다.
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
-> row를 drop한 후 index는 재편되지 않음
titanic_df = titanic_df.drop('Fare', axis=1, inplace=False)
titanic_df.head()
|
PassengerId |
Survived |
Pclass |
Name |
Sex |
Age |
SibSp |
Parch |
Ticket |
Cabin |
Embarked |
| 3 |
4 |
1 |
1 |
Futrelle, M... |
female |
35.0 |
1 |
0 |
113803 |
C123 |
S |
| 4 |
5 |
0 |
3 |
Allen, Mr. ... |
male |
35.0 |
0 |
0 |
373450 |
NaN |
S |
| 5 |
6 |
0 |
3 |
Moran, Mr. ... |
male |
NaN |
0 |
0 |
330877 |
NaN |
Q |
| 6 |
7 |
0 |
1 |
McCarthy, M... |
male |
54.0 |
0 |
0 |
17463 |
E46 |
S |
| 7 |
8 |
0 |
3 |
Palsson, Ma... |
male |
2.0 |
3 |
1 |
349909 |
NaN |
S |
Index 객체
판다스 Index 개요
- 판다스 Index 객체는 RDBMS의 PK(Primary Key)와 유사하게 DataFrame, Series의 레코드를 고유하게 식별하는 객체이다. (하지만 판다스 Index는 별도의 컬럼값이 아님)
- DataFrame/Series 객체는 Index 객체를 포함하지만 DataFrame/Series 객체에 연산 함수를 적용할 때 Index는 연산에서 제외된다.
Index는 오직 식별용으로만 사용된다.
- DataFrame, Series에서 Index 객체만 추출하려면 DataFrame.Index 또는 Series.Index 속성을 통해 가능하다.
- 판다스 Index는 반드시 숫자형 값이 아니어도 되며, 고유한 값을 유지할 수 있다면 문자형/Datetime도 상관없다.
- DataFrame 및 Series에 reset_index() 메서드를 수행하면 새롭게 인덱스를 연속 숫자형으로 할당하며 기존 인덱스는 ‘index’라는 새로운 컬럼명으로 추가한다.
# 원본 파일 재 로딩
titanic_df = pd.read_csv('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]
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
---------------------------------------------------------------------------
TypeError: Index does not support mutable operations
-> index는 고유한 값이어야 함
series_fair = titanic_df['Fare']
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
-> index는 연산에서 제외됨(식별자 역할)
|
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 |
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 |
-> reset_index(inplace=False)를 수행하여 기존 index가 column으로 추가되고 새로운 index가 할당됨
titanic_df['Pclass'].value_counts()
Pclass
3 491
1 216
2 184
Name: count, dtype: int64
print('### before reset_index ###')
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
print('value_counts 객체 변수 타입과 shape:',type(value_counts), value_counts.shape)
new_value_counts_01 = value_counts.reset_index(inplace=False)
print('### After reset_index ###')
print(new_value_counts_01)
print('new_value_counts_01 객체 변수 타입과 shape:',type(new_value_counts_01), new_value_counts_01.shape)
new_value_counts_02 = value_counts.reset_index(drop=True, inplace=False)
print('### After reset_index with drop ###')
print(new_value_counts_02)
print('new_value_counts_02 객체 변수 타입과 shape:',type(new_value_counts_02), new_value_counts_02.shape)
### before reset_index ###
Pclass
3 491
1 216
2 184
Name: count, dtype: int64
value_counts 객체 변수 타입과 shape: <class 'pandas.core.series.Series'> (3,)
### After reset_index ###
Pclass count
0 3 491
1 1 216
2 2 184
new_value_counts_01 객체 변수 타입과 shape: <class 'pandas.core.frame.DataFrame'> (3, 2)
### After reset_index with drop ###
0 491
1 216
2 184
Name: count, dtype: int64
new_value_counts_02 객체 변수 타입과 shape: <class 'pandas.core.series.Series'> (3,)
titanic_df['Pclass'].value_counts().reset_index()
|
Pclass |
count |
| 0 |
3 |
491 |
| 1 |
1 |
216 |
| 2 |
2 |
184 |
# DataFrame의 rename()은 인자로 columns를 dictionary 형태로 받으면 '기존 컬럼명':'신규 컬럼명' 형태로 변환
new_value_counts_01 = titanic_df['Pclass'].value_counts().reset_index()
new_value_counts_01.rename(columns={'index':'Pclass', 'Pclass':'Pclass_count'})
|
Pclass_count |
count |
| 0 |
3 |
491 |
| 1 |
1 |
216 |
| 2 |
2 |
184 |
DataFrame 인덱싱 및 필터링
[]: 컬럼 기반 필터링 또는 불린 인덱싱 필터링 제공
loc[], iloc[]: 명칭/위치 기반 인덱싱 제공
불린 인덱싱(Boolean Indexing): 조건식에 따른 필터링 제공
Pandas DataFrame [] 기능
- []에 단일 컬럼명을 입력하면 컬럼명에 해당하는 Series 객체를 반환
- []에 여러 개의 컬럼명들을 list로 입력하면 컬럼명들에 해당하는 DataFrame 객체를 반환
titanic_df[['Name', 'Age']]
- 하지만 numpy의 ndarray에서의 []는 위치 인덱스 값을 입력하여 해당 위치에 있는 값으로 ndarray를 반환
DataFrame 인덱싱 및 필터링 - loc, iloc
- 명칭(Label) 기반 인덱싱은 컬럼의 명칭을 기반으로 위치를 지정하느 방식이다.
‘컬럼명’ 같이 명칭으로 열 위치를 지정하는 방식이다.(행 위치는 Index 이용)
- 위치(Position) 기반 인덱싱은 0을 출발점으로 하는 가로축, 세로축 좌표 기반의 행과 열 위치를 기반으로 데이터를 지정한다.
따라서 행, 열 위치값으로 정수가 입력된다.(Index를 이용하지 않음)
불린 인덱싱(Boolean Indexing)
- 위치 기반, 명칭 기반 인덱싱 모두 사용할 필요없이 조건식을 [] 안에 기입하여 간편하게 필터링을 수행한다.
titanic_boolean = titanic_df[titanic_df[‘Age’] > 60]
DataFrame의 [ ] 연산자
# DataFrame객체에서 []연산자내에 한개의 컬럼만 입력하면 Series 객체를 반환
series = titanic_df['Name']
print(series.head(3))
print("## type:",type(series), 'shape:', series.shape)
# DataFrame객체에서 []연산자내에 여러개의 컬럼을 리스트로 입력하면 그 컬럼들로 구성된 DataFrame 반환
filtered_df = titanic_df[['Name', 'Age']]
display(filtered_df.head(3))
print("## type:", type(filtered_df), 'shape:', filtered_df.shape)
# DataFrame객체에서 []연산자내에 한개의 컬럼을 리스트로 입력하면 한개의 컬럼으로 구성된 DataFrame 반환
one_col_df = titanic_df[['Name']]
display(one_col_df.head(3))
print("## type:", type(one_col_df), 'shape:', one_col_df.shape)
0 Braund, Mr....
1 Cumings, Mr...
2 Heikkinen, ...
Name: Name, dtype: object
## type: <class 'pandas.core.series.Series'> shape: (891,)
|
Name |
Age |
| 0 |
Braund, Mr.... |
22.0 |
| 1 |
Cumings, Mr... |
38.0 |
| 2 |
Heikkinen, ... |
26.0 |
## type: <class 'pandas.core.frame.DataFrame'> shape: (891, 2)
|
Name |
| 0 |
Braund, Mr.... |
| 1 |
Cumings, Mr... |
| 2 |
Heikkinen, ... |
## type: <class 'pandas.core.frame.DataFrame'> shape: (891, 1)
print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0])
---------------------------------------------------------------------------
KeyError: 0
|
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 |
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 |
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
|
Name |
Year |
Gender |
| one |
Chulmin |
2011 |
Male |
| two |
Eunkyung |
2016 |
Female |
| three |
Jinwoong |
2015 |
Male |
| four |
Soobeom |
2015 |
Male |
# 아래 코드는 오류를 발생합니다.
data_df.iloc[0, 'Name']
---------------------------------------------------------------------------
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: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
-> iloc[]의 값은 숫자형이어야함
print("\n iloc[1, 0] 두번째 행의 첫번째 열 값:", data_df.iloc[1,0])
print("\n iloc[2, 1] 세번째 행의 두번째 열 값:", data_df.iloc[2,1])
print("\n iloc[0:2, [0,1]] 첫번째에서 두번째 행의 첫번째, 두번째 열 값:\n", data_df.iloc[0:2, [0,1]])
print("\n iloc[0:2, 0:3] 첫번째에서 두번째 행의 첫번째부터 세번째 열값:\n", data_df.iloc[0:2, 0:3])
print("\n 모든 데이터 [:] \n", data_df.iloc[:])
print("\n 모든 데이터 [:, :] \n", data_df.iloc[:, :])
iloc[1, 0] 두번째 행의 첫번째 열 값: Eunkyung
iloc[2, 1] 세번째 행의 두번째 열 값: 2015
iloc[0:2, [0,1]] 첫번째에서 두번째 행의 첫번째, 두번째 열 값:
Name Year
one Chulmin 2011
two Eunkyung 2016
iloc[0:2, 0:3] 첫번째에서 두번째 행의 첫번째부터 세번째 열값:
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
모든 데이터 [:]
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
모든 데이터 [:, :]
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
print("\n 맨 마지막 칼럼 데이터 [:, -1] \n", data_df.iloc[:, -1])
print("\n 맨 마지막 칼럼을 제외한 모든 데이터 [:, :-1] \n", data_df.iloc[:, :-1])
맨 마지막 칼럼 데이터 [:, -1]
one Male
two Female
three Male
four Male
Name: Gender, dtype: object
맨 마지막 칼럼을 제외한 모든 데이터 [:, :-1]
Name Year
one Chulmin 2011
two Eunkyung 2016
three Jinwoong 2015
four Soobeom 2015
# iloc[]는 불린 인덱싱을 지원하지 않아서 아래는 오류를 발생.
print("\n ix[data_df.Year >= 2014] \n", data_df.iloc[data_df.Year >= 2014])
---------------------------------------------------------------------------
ValueError: iLocation based boolean indexing cannot use an indexable as a mask
data_df.loc['one', 'Name']
# 다음 코드는 오류를 발생합니다.
data_df.loc[0, 'Name']
---------------------------------------------------------------------------
KeyError: 0
-> index 값이 ‘one’, ‘two’, ‘three’, ‘four’로 지정되어 있으므로 지정된 index 값이 아닌 0을 입력하면 오류가 발생함
print('위치기반 iloc slicing\n', data_df.iloc[0:1, 0],'\n')
print('명칭기반 loc slicing\n', data_df.loc['one':'two', 'Name'])
위치기반 iloc slicing
one Chulmin
Name: Name, dtype: object
명칭기반 loc slicing
one Chulmin
two Eunkyung
Name: Name, dtype: object
-> [0:1]의 경우 0부터 마지막 값에 -1을 한 0까지로 index의 위치가 0인 값만 출력되지만, [‘one’:’two’]의 경우 ‘two’가 문자형으로 -1을 할 수 없기 때문에 index가 ‘one’, ‘two’인 값을 모두 출력함
print('인덱스 값 three인 행의 Name칼럼값:', data_df.loc['three', 'Name'])
print('\n인덱스 값 one 부터 two까지 행의 Name과 Year 칼럼값:\n', data_df.loc['one':'two', ['Name', 'Year']])
print('\n인덱스 값 one 부터 three까지 행의 Name부터 Gender까지의 칼럼값:\n', data_df.loc['one':'three', 'Name':'Gender'])
print('\n모든 데이터 값:\n', data_df.loc[:])
print('\n불린 인덱싱:\n', data_df.loc[data_df.Year >= 2014])
인덱스 값 three인 행의 Name칼럼값: Jinwoong
인덱스 값 one 부터 two까지 행의 Name과 Year 칼럼값:
Name Year
one Chulmin 2011
two Eunkyung 2016
인덱스 값 one 부터 three까지 행의 Name부터 Gender까지의 칼럼값:
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
모든 데이터 값:
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
불린 인덱싱:
Name Year Gender
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
pd.set_option('display.max_colwidth', 200)
titanic_df = pd.read_csv('train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60]
print(type(titanic_boolean))
titanic_boolean
<class 'pandas.core.frame.DataFrame'>
|
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 |
titanic_df[titanic_df['Age'] > 60][['Name','Age']].head(3)
|
Name |
Age |
| 33 |
Wheadon, Mr. Edward H |
66.0 |
| 54 |
Ostby, Mr. Engelhart Cornelius |
65.0 |
| 96 |
Goldschmidt, Mr. George B |
71.0 |
titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(3)
|
Name |
Age |
| 33 |
Wheadon, Mr. Edward H |
66.0 |
| 54 |
Ostby, Mr. Engelhart Cornelius |
65.0 |
| 96 |
Goldschmidt, Mr. George B |
71.0 |
titanic_df[ (titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')]
|
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 |
cond1 = titanic_df['Age'] > 60
cond2 = titanic_df['Pclass']==1
cond3 = titanic_df['Sex']=='female'
titanic_df[ cond1 & cond2 & cond3]
|
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 |
-> conda1, conda2, conda3: True/False 값
정렬, Aggregation함수, GroupBy 적용
DataFrame, Series의 정렬 - sort_values()
- DataFrmae의 sort_values() 메소드는 by 인자로 정렬하고자 하는 컬럼값을 입력 받아서 해당 컬럼값으로 DataFrame을 정렬한다.
오름차순 정렬이 기본이며 ascending=True로 설정된다.(내림차순 정렬 시 ascending=False로 설정)
# 이름으로 정렬
titanic_sorted = titanic_df.sort_values(by=['Name'])
titanic_sorted.head(3)
|
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 |
# Pclass와 Name으로 내림차순 정렬
titanic_sorted = titanic_df.sort_values(by=['Pclass', 'Name'], ascending=False)
titanic_sorted.head(3)
|
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을 적용한다.
# DataFrame의 건수를 알고 싶다면 count() 보다는 shape를 이용
titanic_df.count()
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
titanic_df[['Age', 'Fare']].mean()
Age 29.699118
Fare 32.204208
dtype: float64
titanic_df[['Age', 'Fare']].sum()
Age 21205.1700
Fare 28693.9493
dtype: float64
titanic_df[['Age', 'Fare']].count()
Age 714
Fare 891
dtype: int64
groupby() 이용하기
- DataFrame은 Group by 연산을 위해 groupby() 메소드를 제공한다.
- groupby() 메소드는 by 인자로 group by 하려는 컬럼명을 입력 받으면 DataFrameGroupBy 객체를 반환한다.
이렇게 반환된 DataFrameGroupBy 객체에 aggregation 함수를 수행한다.
- 여러개의 컬럼으로 group by 하고자 하면 []내에 컬럼명을 입력한다.
titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby))
<class 'pandas.core.groupby.generic.DataFrameGroupBy'>
titanic_groupby[['Age', 'Fare']]
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001DC13CF99D0>
titanic_groupby[['Age', 'Fare']].count()
|
Age |
Fare |
| Pclass |
|
|
| 1 |
186 |
216 |
| 2 |
173 |
184 |
| 3 |
355 |
491 |
-> DataFrameGroupBy 객체를 DataFrame으로 풀어주기 위해서는 Aggregation 함수를 수행하면 됨
titanic_groupby = titanic_df.groupby('Pclass').count()
titanic_groupby
|
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 |
titanic_groupby = titanic_df.groupby('Pclass')[['PassengerId', 'Survived']].count()
titanic_groupby
|
PassengerId |
Survived |
| Pclass |
|
|
| 1 |
216 |
216 |
| 2 |
184 |
184 |
| 3 |
491 |
491 |
- 서로 다른 aggregation을 적용하려면 서로 다른 aggregation 메소드를 호출해야 한다.
이 경우 aggregation메소드가 많아지면 코드 작성이 번거로워 지므로 DataFrameGroupby의 agg()를 활용한다.
titanic_df.groupby('Pclass')['Age'].max(), titanic_df.groupby('Pclass')['Age'].min()
(Pclass
1 80.0
2 70.0
3 74.0
Name: Age, dtype: float64,
Pclass
1 0.92
2 0.67
3 0.42
Name: Age, dtype: float64)
titanic_df.groupby('Pclass')['Age'].agg([max, min])
|
max |
min |
| Pclass |
|
|
| 1 |
80.0 |
0.92 |
| 2 |
70.0 |
0.67 |
| 3 |
74.0 |
0.42 |
- 서로 다른 컬럼에 서로 다른 aggregation 메소드를 적용할 경우 agg()내에 컬럼과 적용할 메소드를 Dict형태로 입력한다.
agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'}
titanic_df.groupby('Pclass').agg(agg_format)
|
Age |
SibSp |
Fare |
| Pclass |
|
|
|
| 1 |
80.0 |
90 |
84.154687 |
| 2 |
70.0 |
74 |
20.662183 |
| 3 |
74.0 |
302 |
13.675550 |
- agg내의 인자로 들어가는 Dict객체에 동일한 Key값을 가지는 두개의 value가 있을 경우 마지막 value로 update된다.
즉 동일 컬럼에 서로 다른 aggregation을 가지면서 추가적인 컬럼 aggregation이 있을 경우 원하는 결과로 출력되지 않는다.
agg_format={'Age':'max', 'Age':'mean', 'Fare':'mean'}
titanic_df.groupby('Pclass').agg(agg_format)
|
Age |
Fare |
| Pclass |
|
|
| 1 |
38.233441 |
84.154687 |
| 2 |
29.877630 |
20.662183 |
| 3 |
25.140620 |
13.675550 |
titanic_df.groupby(['Pclass']).agg(age_max=('Age', 'max'), age_mean=('Age', 'mean'), fare_mean=('Fare', 'mean'))
|
age_max |
age_mean |
fare_mean |
| Pclass |
|
|
|
| 1 |
80.0 |
38.233441 |
84.154687 |
| 2 |
70.0 |
29.877630 |
20.662183 |
| 3 |
74.0 |
25.140620 |
13.675550 |
titanic_df.groupby('Pclass').agg(
age_max=pd.NamedAgg(column='Age', aggfunc='max'),
age_mean=pd.NamedAgg(column='Age', aggfunc='mean'),
fare_mean=pd.NamedAgg(column='Fare', aggfunc='mean')
)
|
age_max |
age_mean |
fare_mean |
| Pclass |
|
|
|
| 1 |
80.0 |
38.233441 |
84.154687 |
| 2 |
70.0 |
29.877630 |
20.662183 |
| 3 |
74.0 |
25.140620 |
13.675550 |
-> 동일 column에 서로 다른 aggregation을 수행하려면 column과 aggregation 함수별로 column명을 지정해 주면 됨
결손 데이터 처리하기
- isna(): DataFrame의 isna() 메소드는 주어진 컬럼값들이 NaN인지 True/False 값을 반환한다.(NaN이면 True)
- fillna(): Missing 데이터를 인자로 주어진 값으로 대체한다.
isna()
titanic_df.isna().head(3)
|
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 |
titanic_df.isna( ).sum( )
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()
titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')
titanic_df.head(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 |
C000 |
S |
| 1 |
2 |
1 |
1 |
Cumings, Mrs. John Bradley (Florence Briggs Thayer) |
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 |
titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()
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
nunique로 컬럼내 몇건의 고유값이 있는지 파악
print(titanic_df['Name'].value_counts())
(output 생략)
print(titanic_df['Pclass'].nunique())
print(titanic_df['Survived'].nunique())
print(titanic_df['Name'].nunique())
replace로 원본 값을 특정값으로 대체
replace_test_df = pd.read_csv('train.csv')
# Sex의 male값을 Man
replace_test_df['Sex'].replace('male', 'Man')
(output 생략)
replace_test_df['Sex'] = replace_test_df['Sex'].replace({'male':'Man', 'female':'Woman'})
replace_test_df['Cabin'] = replace_test_df['Cabin'].replace(np.nan, 'C001')
-> NULL 값을 ‘C001’로 대체
replace_test_df['Cabin'].value_counts(dropna=False)
-> value_counts(dropna=False): NULL값도 counts
(output 생략)
apply lambda 식으로 데이터 가공
- 판다스는 apply 함수에 lambda 식을 결합해 DataFrame이나 Series의 레코드별로 데이터를 가공하는 기능을 제공한다.
판다스의 경우 컬럼에 일괄적으로 데이터 가공을 하는 것이 속도 면에서 더 빠르나 복잡한 데이터 가공이 필요할 경우 어쩔 수 없이 apply lambda를 이용한다.
titanic_df['Name_len'] = titanic_df['Name'].apply(lambda x: len(x))
def get_square(a):
return a**2
print('3의 제곱은:',get_square(3))
lambda_square = lambda x : x ** 2
print('3의 제곱은:',lambda_square(3))
a=[1,2,3]
squares = map(lambda x : x**2, a)
list(squares)
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 Thayer) |
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(8)
|
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 |
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()
Age_cat
Adult 786
Child 83
Elderly 22
Name: count, 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
# 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()
|
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 |