Updated:

import pandas as pd
import numpy as np

msg = "{}:\n{}\n"

1. Column selection, addition, deletion, insertion

1.1. Column Selection

df라는 이름으로 DataFrame을 만들었다고 가정해보자.

이 때 DataFrame의 각 column은 df[col_name](or df.col_name)으로 접근할 수 있다.

d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])

print(msg.format("df",df))
print(msg.format("df['one']",df['one']))
print(msg.format("df['three']",df['three']))
print(msg.format("df[['one','three']]",df[['one','three']]))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

df['one']:
a    1
b    2
c    3
d    4
Name: one, dtype: int64

df['three']:
a     9
b    10
c    11
d    12
Name: three, dtype: int64

df[['one','three']]:
   one  three
a    1      9
b    2     10
c    3     11
d    4     12

1.2. Column addition

column을 DataFrame에 새로 추가하는 방법은 dictionary에 새로운 원소를 추가하는 방법과 같다.

df[new_column_name] = data: data는 기존 column으로 만들기도 하고 ndarray, list 로도 만들 수 있다.

d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])
print(msg.format("df",df))

df['four'] = df['one'] + df['three']
print(msg.format("df",df))

df['five'] = np.arange(17,21)
print(msg.format("df",df))

df['six'] = [21,22,23,24]
print(msg.format("df",df))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

df:
   one  two  three  four
a    1    5      9    10
b    2    6     10    12
c    3    7     11    14
d    4    8     12    16

df:
   one  two  three  four  five
a    1    5      9    10    17
b    2    6     10    12    18
c    3    7     11    14    19
d    4    8     12    16    20

df:
   one  two  three  four  five  six
a    1    5      9    10    17   21
b    2    6     10    12    18   22
c    3    7     11    14    19   23
d    4    8     12    16    20   24

1.3. Column deletion

DataFrame에서 Column을 삭제하는 방법은 del을 이용하는 방법과 pop() 메소드를 사용하는 방법이 있다.

  • del df[column_name]: inplace이기 때문에 df 자체에서 해당 column을 삭제한다.
  • df.pop(column_name): 마찬가지로 inplace이기 때문에 df 내에서 해당 column을 삭제한다. 삭제된 column을 반환한다.
  • df.drop([col_name1, col_name2],axis=1): 해당하는 column을 drop한 DataFrame을 반환환다. (마치 drop처럼 작동한다.)
d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])
print(msg.format("df",df))

del df['two']
print(msg.format("df",df))

three = df.pop("three")
print(msg.format("three",three))

print(msg.format("df",df))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

df:
   one  three
a    1      9
b    2     10
c    3     11
d    4     12

three:
a     9
b    10
c    11
d    12
Name: three, dtype: int64

df:
   one
a    1
b    2
c    3
d    4

1.4. Column insertion

DataFrame에 Column을 원하는 위치에 insertion하는 방법은 DataFrame.insert() 메소드를 이용하면 된다.

df.insert(loc,column_name,value): inplace 방식으로 df에 column을 삽입한다.

  • loc : 원하는 위치
  • column_name : column name(column label)
  • value : data를 가리킨다. (int, Series, or array-like)
d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])
print(msg.format("df",df))

df.insert(1,"inserted",np.arange(21,25))
print(msg.format("df",df))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

df:
   one  inserted  two  three
a    1        21    5      9
b    2        22    6     10
c    3        23    7     11
d    4        24    8     12

2. Row Handling

2.1. Basic Row Handling (DataFrame Handling)

다음 는 기본적으로 row를 다루는 방법들이다.

Operation Syntax Result
Select row by label(index) df.loc[label] Series
Select row by integer location df.iloc[loc] Series
Slice rows df[5:10] DataFrame
Select rows by boolean vector df[bool_vec] DataFrame
d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])
print(msg.format("df",df))

a_row = df.loc['a']
print(msg.format("row a",a_row))

a_c_row = df.loc[['a','c']]
print(msg.format("row a,c",a_c_row))

b_row = df.iloc[1]
print(msg.format("row b",b_row))

b_c_row = df.iloc[[1,2]]
print(msg.format("row b,c",b_c_row))

a_b_row = df[:2]
print(msg.format("row a,b",a_b_row))

row_larger_4 = df[df['one'] >= 4]
print(msg.format("df['one'] >= 4인 row",row_larger_4))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

row a:
one      1
two      5
three    9
Name: a, dtype: int64

row a,c:
   one  two  three
a    1    5      9
c    3    7     11

row b:
one       2
two       6
three    10
Name: b, dtype: int64

row b,c:
   one  two  three
b    2    6     10
c    3    7     11

row a,b:
   one  two  three
a    1    5      9
b    2    6     10

df['one'] >= 4인 row:
   one  two  three
d    4    8     12

row를 삭제하는 방법은 df.drop()을 이용하는 방법이 있다.

df.drop(labels, axis=0)

  • labels : 삭제하고 싶은 label을 list형태로 묶어준다.
  • axis=0(default)인 경우 row를 기준으로 axis=1인 경우 column을 기준으로 drop한다.
d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])
print(msg.format("df",df))

print(msg.format("df.drop(['a','d'])",df.drop(['a','d'])))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

df.drop(['a','d']):
   one  two  three
b    2    6     10
c    3    7     11
d = {"one": np.arange(1,5),
     "two": np.arange(5,9),
     "three":np.arange(9,13)}

df = pd.DataFrame(d,index=['a','b','c','d'])
print(msg.format("df",df))

print(msg.format("df>=4",df>=4))

print(msg.format("df[df>=0]", df[df>=4]))
df:
   one  two  three
a    1    5      9
b    2    6     10
c    3    7     11
d    4    8     12

df>=4:
     one   two  three
a  False  True   True
b  False  True   True
c  False  True   True
d   True  True   True

df[df>=0]:
   one  two  three
a  NaN    5      9
b  NaN    6     10
c  NaN    7     11
d  4.0    8     12

2.2. df.head(), df.tail()

  • df.head(): 앞에서부터 5개의 row를 불러옴
  • df.head(number): 앞에서부터 number개의 row를 불러옴
  • df.tail(): 뒤에서부터 5개의 row를 불러옴
  • df.head(number): 뒤에서부터 number개의 row를 불러옴
data = np.random.randint(1,100,(6,5))

df = pd.DataFrame(data,index = list('abcdef'), columns=['col ' + str(i) for i in range(1,6)])
print(msg.format("df",df))

print(msg.format("df.head()",df.head()))
print(msg.format("df.head(3)",df.head(3)))

print(msg.format("df.tail()",df.tail()))
print(msg.format("df.tail(2)",df.tail(2)))
df:
   col 1  col 2  col 3  col 4  col 5
a     50     19     26     81     25
b     23     54     81     85     43
c      3     74      9     30     37
d     64     87     53     70     43
e     47     13     39     32     23
f      8     54     70     75      8

df.head():
   col 1  col 2  col 3  col 4  col 5
a     50     19     26     81     25
b     23     54     81     85     43
c      3     74      9     30     37
d     64     87     53     70     43
e     47     13     39     32     23

df.head(3):
   col 1  col 2  col 3  col 4  col 5
a     50     19     26     81     25
b     23     54     81     85     43
c      3     74      9     30     37

df.tail():
   col 1  col 2  col 3  col 4  col 5
b     23     54     81     85     43
c      3     74      9     30     37
d     64     87     53     70     43
e     47     13     39     32     23
f      8     54     70     75      8

df.tail(2):
   col 1  col 2  col 3  col 4  col 5
e     47     13     39     32     23
f      8     54     70     75      8

3. DataFrame describe, transpose, sorting

3.1. DataFrame Describe

column별로 기본적인 statistics를 보여준다.

data = np.random.randint(1,100,(6,5))

df = pd.DataFrame(data,index = list('abcdef'), columns=['col ' + str(i) for i in range(1,6)])
print(msg.format("df",df))

df.describe()
df:
   col 1  col 2  col 3  col 4  col 5
a     78     67     36     12     26
b     35      1     55     55     46
c      9     53     77     75     78
d     95     28      3     22     19
e      2     34     10     42     24
f     51     30     68      7     91
col 1 col 2 col 3 col 4 col 5
count 6.000000 6.000000 6.000000 6.000000 6.000000
mean 45.000000 35.500000 41.500000 35.500000 47.333333
std 37.067506 22.704625 30.494262 26.568779 30.500273
min 2.000000 1.000000 3.000000 7.000000 19.000000
25% 15.500000 28.500000 16.500000 14.500000 24.500000
50% 43.000000 32.000000 45.500000 32.000000 36.000000
75% 71.250000 48.250000 64.750000 51.750000 70.000000
max 95.000000 67.000000 77.000000 75.000000 91.000000

3.2. DataFrame Transpose

df.T를 이용하면 Transpose된 DataFrame을 확인할 수 있다.

data = np.random.randint(1,100,(6,5))

df = pd.DataFrame(data,index = list('abcdef'), columns=['col ' + str(i) for i in range(1,6)])
print(msg.format("df",df))

print(msg.format("df transpose",df.T))
df:
   col 1  col 2  col 3  col 4  col 5
a     90     36     11     46     42
b      2     92     50      7      7
c     44     87     15     51     77
d     37     37     65     91     55
e     79     80     45     66     97
f     54     11     26     47      9

df transpose:
        a   b   c   d   e   f
col 1  90   2  44  37  79  54
col 2  36  92  87  37  80  11
col 3  11  50  15  65  45  26
col 4  46   7  51  91  66  47
col 5  42   7  77  55  97   9

3.3. DataFrame Sorting

DataFrame을 sorting하는 방법은 label을 이용한 방법이 있고 주어진 value(data)를 기준으로 하는 방법이 있다.

df.sort_index(axis=0,ascending=True)

  • label을 기준으로 sorting한다.
  • axis=1 이면 column label을 기준으로 sorting을 한다.
  • ascending=False이면 descending order로 정렬한다.

df.sort_values(by, axis=0,asceding=True)

  • by의 data(value)를 기준으로 정렬한다. by에는 index(row label), columns(column label)이 온다.
  • index 기준으로 정렬하고 싶다면 axis=1로 해야한다. (index를 기준으로 column이 정렬되기 때문이다. NumPy의 axis를 따른다.)
  • column 기준으로 정렬하고 싶다면 axis=0(default)로 해야한다. (column을 기준으로 row가 정렬되기 때문이다. NumPy의 axis를 따른다.)
  • ascending=False이면 descending order로 정렬한다.
data = np.random.randint(1,100,(6,5))

df = pd.DataFrame(data,index = list('abcdef'), columns=['col ' + str(i) for i in range(1,6)])
print(msg.format("df",df))

sort_row_desc = df.sort_index(ascending=False)
print(msg.format("sort_row_desc",sort_row_desc))

sort_col_desc = df.sort_index(axis=1,ascending=False)
print(msg.format("sort_col_desc",sort_col_desc))

sort_by_col3 = df.sort_values(by='col 3')
print(msg.format('sort_by_col3',sort_by_col3))

sort_by_e = df.sort_values(by='e', axis=1, ascending=False)
print(msg.format("sort_by_e",sort_by_e))
df:
   col 1  col 2  col 3  col 4  col 5
a     87     36     81     57     59
b     23     55     73     48     40
c      3     91     79     41     51
d     54      8     24     36     30
e     76     77     14     29     53
f     98     88     29     96     88

sort_row_desc:
   col 1  col 2  col 3  col 4  col 5
f     98     88     29     96     88
e     76     77     14     29     53
d     54      8     24     36     30
c      3     91     79     41     51
b     23     55     73     48     40
a     87     36     81     57     59

sort_col_desc:
   col 5  col 4  col 3  col 2  col 1
a     59     57     81     36     87
b     40     48     73     55     23
c     51     41     79     91      3
d     30     36     24      8     54
e     53     29     14     77     76
f     88     96     29     88     98

sort_by_col3:
   col 1  col 2  col 3  col 4  col 5
e     76     77     14     29     53
d     54      8     24     36     30
f     98     88     29     96     88
b     23     55     73     48     40
c      3     91     79     41     51
a     87     36     81     57     59

sort_by_e:
   col 2  col 1  col 5  col 4  col 3
a     36     87     59     57     81
b     55     23     40     48     73
c     91      3     51     41     79
d      8     54     30     36     24
e     77     76     53     29     14
f     88     98     88     96     29

Leave a comment