02.판다스 Pandas

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

import pandas as pd

read_csv()

  • read_csv()를 이용하여 csv 파일을 편리하게 DataFrame으로 로딩함.

  • read_csv()의 sep인자를 콤마(,)가 아닌 다른 분리자로 변경하여 다른 유형의 파일로 로드가 가능함.

from google.colab import drive
drive.mount('/content/drvie')
Mounted at /content/drvie
df = pd.read_csv('/content/drvie/MyDrive/Kaggle/Data set/titanic/train.csv')
print('Titanic 변수 type:', type(df))
Titanic 변수 type: <class 'pandas.core.frame.DataFrame'>
  • DataFrame의 맨 앞 일부 데이터만 추출합니다.
df.head()
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': ['Jihun','Eunyung','Soobeom','Eunkyung'],
        'Year':[2011,2016,2015,2015],
        'Gender':['Male','Female','male','Female']}


# 딕셔너리 파일을 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     Jihun  2011    Male
1   Eunyung  2016  Female
2   Soobeom  2015    male
3  Eunkyung  2015  Female
##############################
       Name  Year  Gender  Age
0     Jihun  2011    Male  NaN
1   Eunyung  2016  Female  NaN
2   Soobeom  2015    male  NaN
3  Eunkyung  2015  Female  NaN
##############################
           Name  Year  Gender
one       Jihun  2011    Male
two     Eunyung  2016  Female
three   Soobeom  2015    male
four   Eunkyung  2015  Female
##############################

DataFrame의 컬럼명과 인덱스

print("columns:", df.columns)
print("index:", df.index)
print("index value:", 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 = df['Name']
print(series.head(3))
print("## type:",type(series))

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

# DataFrame객체에ㅓ []연산자내에 한개의 컬럼을 리스트로 입력하면 한개의 컬럼으로 구성된 DataFrame 반환
one_col_df = 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 크기 : ', df.shape)
DataFrame 크기 :  (891, 12)

info

  • DataFrame내의 컬럼명, 데이터타입, Null건수, 데이터 건수 정보를 제공함.
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB

describe()

  • 데이터값들의 평균,표준편차, 4분위 분포도를 제공함. 숫자형 컬럼들에 대해서 해당 정보를 제공함.
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로 변환한 뒤 호출한다.
df['Pclass'].value_counts()
3    491
1    216
2    184
Name: Pclass, dtype: int64
titanic_Pclass = 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
print(type(df['Pclass'].value_counts()))
print(df['Pclass'].value_counts())
<class 'pandas.core.series.Series'>
3    491
1    216
2    184
Name: Pclass, dtype: int64

sort_values()

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

df[['Name','Age']].sort_values(by='Age')
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
... ... ... ...
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차원 리스트로 만든 DataFrame:\n', df_array1)

array1 shape: (3,)
1차원 리스트로 만든 DataFrame:
    col1
0     1
1     2
2     3
1차원 리스트로 만든 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)
dict1 = {'col1':[1, 11],
         'col2':[2, 22],
         'col3':[3, 33]}

df_dict = pd.DataFrame(dict1)
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을 리스트로 변환
list3 = df_dict.values.tolist()
print('df_dict.values.tolist() 타입:', type(list3))
print(list3)
df_dict.values.tolist() 타입: <class 'list'>
[[1, 2, 3], [11, 22, 33]]
df_dict.values.tolist() 타입: <class 'list'>
[[1, 2, 3], [11, 22, 33]]

DataFrame의 컬럼 데이터 셋 Access

  • DataFrame의 컬럼 데이터 세트 생성과 수정은 [] 연산자를 이용해 쉽게 할 수 있다. 새로운 컬럼에 값을 할당하려면 DataFrame[]내에 새로운 컬럼명을 입력하고 값을 할당해주기만 하면 된다.
df['Age_0'] = 0
df.head()
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
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S 0
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S 0
df['Age_by_10'] = df['Age']*10
df['Family_No'] = df['SibSp'] + df['Parch'] + 1
df.head()
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
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S 0 350.0 2
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S 0 350.0 1
# 기존 컬럼에 값을 업데이트 하려면 해당 컬럼에 업데이트값을 그대로 지정하면 된다.

df['Age_by_10'] = df['Age_by_10'] + 100
df.head()
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
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S 0 450.0 2
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S 0 450.0 1

DataFrame 데이터 삭제

  • axis에 따른 삭제
drop_df = df.drop('Age_0',axis=1)
drop_df.head()
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
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S 450.0 2
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S 450.0 1
  • axis=0은 row방향으로 데이터를 삭제한다.
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 15)
print('#### before axis 0 drop ####')
print(df.head(6))

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

print('#### after axis 0 drop ####')
print(df.head(3))
#### before axis 0 drop ####
   PassengerId  Survived  Pclass  ... Age_0 Age_by_10  Family_No
3            4         1       1  ...     0     450.0          2
4            5         0       3  ...     0     450.0          1
5            6         0       3  ...     0       NaN          1
6            7         0       1  ...     0     640.0          1
7            8         0       3  ...     0     120.0          5
8            9         1       3  ...     0     370.0          3

[6 rows x 15 columns]
#### after axis 0 drop ####
   PassengerId  Survived  Pclass  ... Age_0 Age_by_10  Family_No
3            4         1       1  ...     0     450.0          2
4            5         0       3  ...     0     450.0          1
5            6         0       3  ...     0       NaN          1

[3 rows x 15 columns]

Index 객체

# 원본파일 재 로딩
titanic_df = pd.read_csv('/content/drvie/MyDrive/Kaggle/Data set/titanic/train.csv')

# Index 객체 추출
index = titanic_df.index
print(index)

# index객체를 실제값 array로 반환
print('Index 객에 array값: \n',index.values) # 인덱스는 1차원 데이터다.
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(index.values))
print(index.values.shape)
print(index[:5].values)
print(index.values[:5])
print(index[6])
<class 'numpy.ndarray'>
(891,)
[0 1 2 3 4]
[0 1 2 3 4]
6

Aggregation 함수 및 GroupBy 적용

  • Aggregation 함수 적용
## NaN 값은 count에서 제외
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(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)
<class 'pandas.core.groupby.generic.DataFrameGroupBy'>
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f3f8b2960d0>
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
print(type(titanic_groupby))
print(titanic_groupby.shape)
print(titanic_groupby.index)
<class 'pandas.core.frame.DataFrame'>
(3, 11)
Int64Index([1, 2, 3], dtype='int64', name='Pclass')
titanic_groupby = titanic_df.groupby(by='Pclass')[['PassengerId', 'Survived']].count()
titanic_groupby
PassengerId Survived
Pclass
1 216 216
2 184 184
3 491 491
titanic_df[['Pclass','PassengerId', 'Survived']].groupby('Pclass').count()
PassengerId Survived
Pclass
1 216 216
2 184 184
3 491 491
titanic_df.groupby('Pclass')['Pclass'].count()
titanic_df['Pclass'].value_counts()
3    491
1    216
2    184
Name: Pclass, dtype: int64
  • 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])
max min
Pclass
1 80.0 0.92
2 70.0 0.67
3 74.0 0.42

apply lambda 식으로 데이터 가공

  • 파이썬 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.... 23
1 Cumings, Mr... 51
2 Heikkinen, ... 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.0 Adult
1 38.0 Adult
2 26.0 Adult
3 35.0 Adult
4 35.0 Adult
5 NaN Adult
6 54.0 Adult
7 2.0 Child
8 27.0 Adult
9 14.0 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      609
Elderly    199
Child       83
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

업데이트:

댓글남기기