판다스(Pandas)
read_csv()
- read_csv()를 이용하여 csv파일을 편리하게 DataFrame으로 로딩한다.
- read_csv()의 sep 인자를 콤마(,)가 아닌 다른 분리자로 변경하여 다른 유형의 파일로 로드 가능
titanic_df = pd.read_csv("titanic_train.csv")
print("titanic 변수 type : {}".format(type(titanic_df)))
titanic 변수 type : <class 'pandas.core.frame.DataFrame'>
head()
- DataFrame의 맨 앞 일부 데이터만 추출한다.
- default값은 5
- 가장 왼쪽에 있는 column이 index여서 column명이 없다.
|
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 |
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 |
DataFrame의 생성
dic1 = {"Name" : ["Dowon", "Junho", "Youngsu", "Bomi"],
"Year" : [2011, 2016, 2015, 2015],
"Gender" : ["Male", "Female", "Male", "Male"]}
# Dictionary를 DataFrame으로 변환
data_df = pd.DataFrame(dic1)
print(data_df)
print("-" * 30)
print("-" * 30)
# 새로운 column명을 추가
data_df = pd.DataFrame(dic1, columns=["Name", "Year", "Gender", "Age"])
print(data_df)
print("-" * 30)
print("-" * 30)
# 인덱스를 새로운 값으로 할당
data_df = pd.DataFrame(dic1, index = ["one", "two", "three", "four"])
print(data_df)
Name Year Gender
0 Dowon 2011 Male
1 Junho 2016 Female
2 Youngsu 2015 Male
3 Bomi 2015 Male
------------------------------
------------------------------
Name Year Gender Age
0 Dowon 2011 Male NaN
1 Junho 2016 Female NaN
2 Youngsu 2015 Male NaN
3 Bomi 2015 Male NaN
------------------------------
------------------------------
Name Year Gender
one Dowon 2011 Male
two Junho 2016 Female
three Youngsu 2015 Male
four Bomi 2015 Male
DataFrame의 컬럼명과 인덱스
print("columns : {}".format(titanic_df.columns))
print("index : {}".format(titanic_df.index))
print("index value : {}".format(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]
- index ~> 인덱스의 범위를 반환
- index.value ~> 인덱스의 값들을 반환
DataFrame에서 Series 추출 및 DataFrame 필터링 추출
series = titanic_df["Name"]
print(series.head(3))
print("")
print("## type : {}".format(type(series)))
print("")
filtered_df = titanic_df[["Name", "Age"]]
print(filtered_df.head(3))
print("## type : {}".format(type(filtered_df)))
print("")
one_col_df = titanic_df[["Name"]]
print(one_col_df.head(3))
print("## type : {}".format(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'>
- 일정 column의 Data를 추출할 때, 그냥 Key값 1개만 입력하면 Series로 반환이 된다.
- 만약, [Key]로 1개만 입력하게 되면 DataFrame으로 반환이 된다.
shape
- DataFrame의 행과 열 크기를 가지고 있는 속성
print("DataFrame 크기 : {}".format(titanic_df.shape))
- column 이 12이다. index는 column에 포함되지 않는다.
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 객체에서만 호출 될 수 있으므로 반드시 DataFrame을 단일 컬럼으로 입력하여 Seires로 변환한 뒤 호출합니다.
value_counts = titanic_df["Pclass"].value_counts()
print(value_counts)
print("")
print(type(value_counts))
3 491
1 216
2 184
Name: Pclass, dtype: int64
<class 'pandas.core.series.Series'>
sort_values() by = 정렬컬럼, ascending = True 또는 False로 오름차순/내림차순 정렬
titanic_df.sort_values(by = "Pclass", ascending = False)
# Pclass에 대해서 내림차순으로 정렬
|
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 |
511 |
512 |
0 |
3 |
Webber, Mr. James |
male |
NaN |
0 |
0 |
SOTON/OQ 3101316 |
8.0500 |
NaN |
S |
500 |
501 |
0 |
3 |
Calic, Mr. Petar |
male |
17.0 |
0 |
0 |
315086 |
8.6625 |
NaN |
S |
501 |
502 |
0 |
3 |
Canavan, Miss. Mary |
female |
21.0 |
0 |
0 |
364846 |
7.7500 |
NaN |
Q |
502 |
503 |
0 |
3 |
O'Sullivan, Miss. Bridget Mary |
female |
NaN |
0 |
0 |
330909 |
7.6292 |
NaN |
Q |
... |
... |
... |
... |
... |
... |
... |
... |
... |
... |
... |
... |
... |
102 |
103 |
0 |
1 |
White, Mr. Richard Frasar |
male |
21.0 |
0 |
1 |
35281 |
77.2875 |
D26 |
S |
710 |
711 |
1 |
1 |
Mayne, Mlle. Berthe Antonine ("Mrs de Villiers") |
female |
24.0 |
0 |
0 |
PC 17482 |
49.5042 |
C90 |
C |
711 |
712 |
0 |
1 |
Klaber, Mr. Herman |
male |
NaN |
0 |
0 |
113028 |
26.5500 |
C124 |
S |
712 |
713 |
1 |
1 |
Taylor, Mr. Elmer Zebley |
male |
48.0 |
1 |
0 |
19996 |
52.0000 |
C126 |
S |
445 |
446 |
1 |
1 |
Dodge, Master. Washington |
male |
4.0 |
0 |
2 |
33638 |
81.8583 |
A34 |
S |
891 rows × 12 columns
titanic_df[["Name", "Age"]].sort_values(by = "Age", ascending = True)
|
Name |
Age |
803 |
Thomas, Master. Assad Alexander |
0.42 |
755 |
Hamalainen, Master. Viljo |
0.67 |
644 |
Baclini, Miss. Eugenie |
0.75 |
469 |
Baclini, Miss. Helene Barbara |
0.75 |
78 |
Caldwell, Master. Alden Gates |
0.83 |
... |
... |
... |
859 |
Razi, Mr. Raihed |
NaN |
863 |
Sage, Miss. Dorothy Edith "Dolly" |
NaN |
868 |
van Melkebeke, Mr. Philemon |
NaN |
878 |
Laleff, Mr. Kristo |
NaN |
888 |
Johnston, Miss. Catherine Helen "Carrie" |
NaN |
891 rows × 2 columns
- 만약, Pclass에 대해서 먼저 정렬을 한 후에, 다시 나이에 대해서 정렬을 하고 싶다면 밑에 코드와 같이 작성
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 |
... |
... |
... |
... |
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_name = ["col1"]
list1 = [1, 2, 3]
array1 = np.array(list1)
print("array1 shape : {}".format(array1.shape))
print("")
df_list1 = pd.DataFrame(list1, columns = col_name)
print("1차원 리스트로 만든 DataFrame : \n{}".format(df_list1))
print("")
df_array1 = pd.DataFrame(array1, columns = col_name)
print("1차원 ndarray로 만든 DataFrame : \n{}".format(df_array1))
array1 shape : (3,)
1차원 리스트로 만든 DataFrame :
col1
0 1
1 2
2 3
1차원 ndarray로 만든 DataFrame :
col1
0 1
1 2
2 3
- list와 ndarray를 DataFrame으로 변환하기 위해서는 pd.DataFrame을 사용
col_name2 = ["col1", "col2", "col3"]
list2 = [[1, 2, 3], [11, 12, 13]]
array2 = np.array(list2)
print("list2 : \n{}".format(list2))
print("")
print("array2 : \n{}".format(array2))
print("")
df_list2 = pd.DataFrame(list2, columns = col_name2)
print("2차원 list2로 만든 DataFrame : \n{}".format(df_list2))
print("")
df_array2 = pd.DataFrame(array2, columns = col_name2)
print("2차원 array2로 만든 DataFrame : \n{}".format(df_array2))
list2 :
[[1, 2, 3], [11, 12, 13]]
array2 :
[[ 1 2 3]
[11 12 13]]
2차원 list2로 만든 DataFrame :
col1 col2 col3
0 1 2 3
1 11 12 13
2차원 array2로 만든 DataFrame :
col1 col2 col3
0 1 2 3
1 11 12 13
딕셔너리(dict)에서 DataFrame 변환
dict = {"col1" : [1, 11], "col2" : [2, 12], "col3" : [3, 13]}
df_dict = pd.DataFrame(dict)
print("딕셔너리(dict)로 만든 DataFrame : \n{}".format(df_dict))
딕셔너리(dict)로 만든 DataFrame :
col1 col2 col3
0 1 2 3
1 11 12 13
DataFrame을 ndarray로 변환
print("초기 DataFrame : \n{}".format(df_dict))
array3 = df_dict.values
print("")
print("DataFrame을 ndarray로 변환 : \n{}".format(array3))
print("")
print("df_dict.values 타입 : {}".format(type(array3)))
print("df_dict.values shape : {}".format(array3.shape))
초기 DataFrame :
col1 col2 col3
0 1 2 3
1 11 12 13
DataFrame을 ndarray로 변환 :
[[ 1 2 3]
[11 12 13]]
df_dict.values 타입 : <class 'numpy.ndarray'>
df_dict.values shape : (2, 3)
DataFrame을 리스트로 변환
print("초기의 DataFrame : \n{}".format(df_dict))
print("")
# DataFrame을 리스트로 만들기
list3 = df_dict.values.tolist()
print("DataFrame에서 리스트로 변환 : \n{}".format(list3))
초기의 DataFrame :
col1 col2 col3
0 1 2 3
1 11 12 13
DataFrame에서 리스트로 변환 :
[[1, 2, 3], [11, 12, 13]]
DataFrame을 딕셔너리로 변환
print("초기의 DataFrame : \n{}".format(df_dict))
print("")
dict3 = df_dict.to_dict("list")
print("DataFrame에서 딕셔너리로 변환 : \n{}".format(dict3))
초기의 DataFrame :
col1 col2 col3
0 1 2 3
1 11 12 13
DataFrame에서 딕셔너리로 변환 :
{'col1': [1, 11], 'col2': [2, 12], 'col3': [3, 13]}
DataFrame의 column data set 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 |
- “Age_0”이라는 새로운 컬럼이 생겼고 모든 값들은 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_0"] = titanic_df["Age_0"] + 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 |
1 |
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 |
1 |
380.0 |
2 |
2 |
3 |
1 |
3 |
Heikkinen, Miss. Laina |
female |
26.0 |
0 |
0 |
STON/O2. 3101282 |
7.9250 |
NaN |
S |
1 |
260.0 |
1 |
DataFrame 데이터 삭제
titanic_drop_df = titanic_df.drop("Age_0", axis = 1, inplace = False)
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 |
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 |
380.0 |
2 |
2 |
3 |
1 |
3 |
Heikkinen, Miss. Laina |
female |
26.0 |
0 |
0 |
STON/O2. 3101282 |
7.9250 |
NaN |
S |
260.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 |
1 |
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 |
1 |
380.0 |
2 |
2 |
3 |
1 |
3 |
Heikkinen, Miss. Laina |
female |
26.0 |
0 |
0 |
STON/O2. 3101282 |
7.9250 |
NaN |
S |
1 |
260.0 |
1 |
drop_result = titanic_df.drop(["Age_0", "Age_by_10", "Family_No"], axis = 1, inplace = True)
print("inplace = True 로 drop 후 반환된 값 : {}",format(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 일 경우 row방향으로 데이터 삭제
- axis = 1 일 경우 column방향으로 데이터 삭제
- inplace가 False일 때는 기존의 DataFrame에는 변화가 없다.
- inplace가 True일 때는 기존의 DataFrame이 변하고, 변환되는 값은 None이다.
print("#### before axis 0 drop ####")
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. 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 |
titanic_df.drop([0, 1, 2], axis = 0, inplace = True)
titanic_df.head(3)
|
PassengerId |
Survived |
Pclass |
Name |
Sex |
Age |
SibSp |
Parch |
Ticket |
Fare |
Cabin |
Embarked |
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 |
5 |
6 |
0 |
3 |
Moran, Mr. James |
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 객체를 실제 값 array로 반환
print("index 객체 array의 값 : {}".format(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
indexes[0] = 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 |
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 값 : {}".format(series_fair.max()))
print("Fair Series Sum 값 : {}".format(sum(series_fair)))
print("")
print((series_fair+3).head(3))
Fair Series Max 값 : 512.3292
Fair Series Sum 값 : 28693.949299999967
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. Owen Harris |
male |
22.0 |
1 |
0 |
A/5 21171 |
7.2500 |
NaN |
S |
1 |
1 |
2 |
1 |
1 |
Cumings, Mrs. John Bradley (Florence Briggs Th... |
female |
38.0 |
1 |
0 |
PC 17599 |
71.2833 |
C85 |
C |
2 |
2 |
3 |
1 |
3 |
Heikkinen, Miss. Laina |
female |
26.0 |
0 |
0 |
STON/O2. 3101282 |
7.9250 |
NaN |
S |
print("### before reset_index ###")
value_counts = titanic_df["Pclass"].value_counts()
print(value_counts)
print("value_counts 객체 변수 타입 : {}".format(type(value_counts)))
print("")
new_value_counts = value_counts.reset_index(inplace = False)
print("### after reset_index ###")
print(new_value_counts)
print("new_value_counts 객체 변수 타입 : {}".format(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'>