5. Handling Missing Data(결측치 다루기)
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))

Handling Missing Data

In [2]:
import pandas as pd
import numpy as np
In [3]:
# 임의의 데이터프레임 생성
df = pd.DataFrame( [ [np.nan, 2, np.nan, 0], 
                     [3, 4, np.nan, 1],
                     [np.nan, np.nan, np.nan, 5] ],
                                 columns = list('ABCD') )
df
Out[3]:
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5

dropna(axis = ?, how = ?, inplace = ?) : 결측치 버리기

  • axis = 0 (default) : 행 버리기 ⟷ axis = 1 : 컬럼 버리기
  • how = 'any' (default) : 행 또는 열의 NaN이 하나라도 있을 때 버리기 ⟷ how = 'all' : 전체 행 또는 열의 값이 NaN일 때 버리기
  • inplace = False (default) : drop한 결과 조회만 하기 ⟷ inplace = True : drop한 결과 데이터프레임에 바로 저장
In [4]:
# 전부다 Null인 컬럼 drop
df.dropna(axis=1, how= 'all') 
Out[4]:
A B D
0 NaN 2.0 0
1 3.0 4.0 1
2 NaN NaN 5
In [5]:
# 하나라도 Null이 있는 컬럼 drop
df.dropna(axis=1, how= 'any') 
Out[5]:
D
0 0
1 1
2 5
In [6]:
# 전부다 Null인 열 drop
df.dropna(axis=0, how='all')
Out[6]:
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5
In [7]:
# 하나라도 Null이 있는 열 drop
df.dropna(axis=0, how='any')
Out[7]:
A B C D


df.fillna : NaN 을 지정해준 값으로 채워줌

In [8]:
# 결측치 0으로 채우기
df.fillna(0)
Out[8]:
A B C D
0 0.0 2.0 0.0 0
1 3.0 4.0 0.0 1
2 0.0 0.0 0.0 5
In [9]:
# 딕셔너리를 사용해서 컬럼별로 지정값으로 채우기
values = { 'A' : 0, 'B': 1, 'C': 2, 'D': 3}
df.fillna(value=values)
Out[9]:
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 2.0 1
2 0.0 1.0 2.0 5
In [10]:
# 결측치를 중앙값으로 채우기
fill_na_value = df['D'].median()
df.fillna(fill_na_value)
Out[10]:
A B C D
0 1.0 2.0 1.0 0
1 3.0 4.0 1.0 1
2 1.0 1.0 1.0 5
In [11]:
# 컬럼별로 결측치 데이터 갯수 확인
df.isnull().sum() 
Out[11]:
A    2
B    1
C    3
D    0
dtype: int64
In [12]:
# 컬럼별로 결측치가 아닌 데이터 갯수 확인
df.notnull().sum()
Out[12]:
A    1
B    2
C    0
D    3
dtype: int64
4. Summarize Data(자료 요약하기)
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))

Summarize Data

In [2]:
import pandas as pd
import seaborn as sns
import numpy as np
In [3]:
# 예제 데이터셋 불러오기
df = sns.load_dataset('iris')
df.shape
Out[3]:
(150, 5)
In [4]:
df.head()
Out[4]:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
In [5]:
# 카테고리형 변수가 각 값별로 데이터가 얼마나 있는지 확인
df['species'].value_counts() 
Out[5]:
virginica     50
setosa        50
versicolor    50
Name: species, dtype: int64
In [6]:
# value_counts() 한 것을 데이터 프레임으로 넣기
df['species'].value_counts().to_frame()
# pd.DataFrame(df['species'].value_counts()) 도 같은 결과
Out[6]:
species
virginica 50
setosa 50
versicolor 50
In [7]:
# 데이터 프레임의 행수 확인
len(df)
# df.shape[0] 도 같은 결과
Out[7]:
150
In [8]:
# 변수의 유니크한 값 개수
df['species'].nunique() 
Out[8]:
3
In [9]:
# describe()를 사용해서 기본 통계값들을 확인할 수 있다.
df.describe()
Out[9]:
sepal_length sepal_width petal_length petal_width
count 150.000000 150.000000 150.000000 150.000000
mean 5.843333 3.057333 3.758000 1.199333
std 0.828066 0.435866 1.765298 0.762238
min 4.300000 2.000000 1.000000 0.100000
25% 5.100000 2.800000 1.600000 0.300000
50% 5.800000 3.000000 4.350000 1.300000
75% 6.400000 3.300000 5.100000 1.800000
max 7.900000 4.400000 6.900000 2.500000
In [10]:
# include = 'all' 인자를 넣어주면 categorical 변수에 대한 값인 unique, top, freq도 조회할 수 있음
df.describe(include='all')
Out[10]:
sepal_length sepal_width petal_length petal_width species
count 150.000000 150.000000 150.000000 150.000000 150
unique NaN NaN NaN NaN 3
top NaN NaN NaN NaN virginica
freq NaN NaN NaN NaN 50
mean 5.843333 3.057333 3.758000 1.199333 NaN
std 0.828066 0.435866 1.765298 0.762238 NaN
min 4.300000 2.000000 1.000000 0.100000 NaN
25% 5.100000 2.800000 1.600000 0.300000 NaN
50% 5.800000 3.000000 4.350000 1.300000 NaN
75% 6.400000 3.300000 5.100000 1.800000 NaN
max 7.900000 4.400000 6.900000 2.500000 NaN
In [11]:
# 문자형(카테고리형) 변수에 대한 통계값을 조회할 수 있음
df.describe(include=[np.object])
Out[11]:
species
count 150
unique 3
top virginica
freq 50
In [12]:
# 수치형 변수에 대한 통계값을 조회할 수 있음
df.describe(include=[np.number])
Out[12]:
sepal_length sepal_width petal_length petal_width
count 150.000000 150.000000 150.000000 150.000000
mean 5.843333 3.057333 3.758000 1.199333
std 0.828066 0.435866 1.765298 0.762238
min 4.300000 2.000000 1.000000 0.100000
25% 5.100000 2.800000 1.600000 0.300000
50% 5.800000 3.000000 4.350000 1.300000
75% 6.400000 3.300000 5.100000 1.800000
max 7.900000 4.400000 6.900000 2.500000
In [13]:
# 해당 컬럼의 값 합계
df['petal_width'].sum()
Out[13]:
179.90000000000003
In [14]:
# 해당 컬럼의 null이 아닌 행의 수
df['petal_width'].count()
Out[14]:
150
In [15]:
# 해당 컬럼의 중위수
df['petal_width'].median()
Out[15]:
1.3
In [16]:
# 해당 컬럼의 평균값
df['petal_width'].mean()
Out[16]:
1.199333333333334
In [17]:
# 데이터 프레임 각 컬럼의 평균값
df.mean()
Out[17]:
sepal_length    5.843333
sepal_width     3.057333
petal_length    3.758000
petal_width     1.199333
dtype: float64
In [18]:
# 4분위수 확인하기
df.quantile([0.25, 0.75])
Out[18]:
sepal_length sepal_width petal_length petal_width
0.25 5.1 2.8 1.6 0.3
0.75 6.4 3.3 5.1 1.8
In [19]:
# 데이터 프레임 각 컬럼의 최댓값
df.max()
Out[19]:
sepal_length          7.9
sepal_width           4.4
petal_length          6.9
petal_width           2.5
species         virginica
dtype: object
In [20]:
# 데이터 프레임 각 컬럼의 최솟값
df.min()
Out[20]:
sepal_length       4.3
sepal_width          2
petal_length         1
petal_width        0.1
species         setosa
dtype: object
In [21]:
# 데이터 프레임 각 컬럼의 분산
df.var()
Out[21]:
sepal_length    0.685694
sepal_width     0.189979
petal_length    3.116278
petal_width     0.581006
dtype: float64
In [22]:
# 데이터 프레임의 각 컬럼의 표준편차
df.std()
Out[22]:
sepal_length    0.828066
sepal_width     0.435866
petal_length    1.765298
petal_width     0.762238
dtype: float64

apply(function)

In [23]:
# 임의의 함수 설정
def smp(x):
    # 뒤에서 세번째까지의 문자를 가져오는 함수
    x = x[-3:]
    return x 
In [24]:
# lambda 익명함수 적용
df['species_3'] = df['species'].apply(lambda x : x[:3]) 
In [25]:
# 설정해둔 함수 적용
df['species_4'] = df['species'].apply(smp) 
In [26]:
df.head()
Out[26]:
sepal_length sepal_width petal_length petal_width species species_3 species_4
0 5.1 3.5 1.4 0.2 setosa set osa
1 4.9 3.0 1.4 0.2 setosa set osa
2 4.7 3.2 1.3 0.2 setosa set osa
3 4.6 3.1 1.5 0.2 setosa set osa
4 5.0 3.6 1.4 0.2 setosa set osa
3. Subset Observations(Columns) (열 데이터 다루기)
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))
In [2]:
import pandas as pd
import seaborn as sns
In [3]:
# 예시 데이터 불러오기
df = sns.load_dataset('iris')
print(df.shape)
df.head()
(150, 5)
Out[3]:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa

데이터프레임에서 특정 컬럼 정보만 불러오기

In [4]:
columns = ['sepal_length', 'sepal_width', 'species']
df[columns].head()
Out[4]:
sepal_length sepal_width species
0 5.1 3.5 setosa
1 4.9 3.0 setosa
2 4.7 3.2 setosa
3 4.6 3.1 setosa
4 5.0 3.6 setosa
In [5]:
# 이 방식에서는 한글이나 특수문자가 들어간 컬럼명을 쓸 수 없음
df.sepal_width.head() 
Out[5]:
0    3.5
1    3.0
2    3.2
3    3.1
4    3.6
Name: sepal_width, dtype: float64
In [6]:
df['sepal_width'].head()
Out[6]:
0    3.5
1    3.0
2    3.2
3    3.1
4    3.6
Name: sepal_width, dtype: float64

정규 표현식으로 특정컬럼 불러오기

df.filter( regex = 'regex' )

  • '\.' : 점( . )을 포함하고 있는 문자열
In [7]:
df.filter(regex='\,').head(3)
Out[7]:
0
1
2
  • 'length$' : 특정문자열(length)로 끝나는 문자열
In [8]:
df.filter(regex='length$').head(3)
Out[8]:
sepal_length petal_length
0 5.1 1.4
1 4.9 1.4
2 4.7 1.3
  • '_' : _ 를 포함하고 있는 문자열
In [9]:
df.filter(regex='_').head(3)
Out[9]:
sepal_length sepal_width petal_length petal_width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
  • '^sepal' : 특정문자열(Sepal)로 시작하는 문자열
In [10]:
df.filter(regex='^sepal').head(3)
Out[10]:
sepal_length sepal_width
0 5.1 3.5
1 4.9 3.0
2 4.7 3.2
  • *'^(?!species$).' : 특정문자열('species')이 없는 문자열
In [11]:
df.filter(regex='^(?!species).*').head(3)
Out[11]:
sepal_length sepal_width petal_length petal_width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
  • '^x[1-5]$' : 특정문자(x)로 시작하고 특정문자(1, 2, 3, 4, 5)로 끝나는 문자열
In [12]:
df.filter(regex='^x[1-5]$').head(3)
Out[12]:
0
1
2

df.loc[ ]와 df.iloc[ ] 비교

In [13]:
df.loc[2:5, 'sepal_width':'petal_width']
Out[13]:
sepal_width petal_length petal_width
2 3.2 1.3 0.2
3 3.1 1.5 0.2
4 3.6 1.4 0.2
5 3.9 1.7 0.4

loc와는 다르게 iloc로 검색을 했을 때 a:b 면 b-1행까지 검색을 함
iloc는 인덱스번호만 입력이 가능함

In [14]:
df.iloc[2:5:,  1:3]
Out[14]:
sepal_width petal_length
2 3.2 1.3
3 3.1 1.5
4 3.6 1.4

loc 를 통해 logic 조건으로 행을 지정하고, 컬럼명을 선택할 수 있음

In [15]:
df.loc[df['sepal_length']>3 , ['sepal_length','sepal_width']].head()
Out[15]:
sepal_length sepal_width
0 5.1 3.5
1 4.9 3.0
2 4.7 3.2
3 4.6 3.1
4 5.0 3.6
2. Subset Observations(Rows) (행 데이터 다루기)
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))
In [2]:
import pandas as pd
import numpy as np
In [3]:
# 데이터프레임 생성
df = pd.DataFrame(
                            {'a' : [4, 5, 6], 
                             'b' : [7, 8, 9],
                             'c' : [6, 9, 12]},
                            index = pd.MultiIndex.from_tuples( [('d', 1), ('d', 2), ('e', 2)] ,
                                                                                     names = ['n', 'v'] )
                                )

df
Out[3]:
a b c
n v
d 1 4 7 6
2 5 8 9
e 2 6 9 12

True/False (불린인덱싱)을 이용한 행 데이터 조회

In [4]:
# 기본적으로  <, >, = 와 같은 연산자를 이용하면 아래와 같이 불린 값이 반환된다.
df['a'] < 6
Out[4]:
n  v
d  1     True
   2     True
e  2    False
Name: a, dtype: bool
In [5]:
# True로 값을 반환한 행에 대해서만 데이터를 불러온다.
df[df['a'] < 6]
Out[5]:
a b c
n v
d 1 4 7 6
2 5 8 9

중복데이터 제거 : df.drop_duplicates( )

In [6]:
# 중복된 행을 가지는 임의의 데이터프레임 생성
df = pd.DataFrame(
                {'a' : [4, 5, 6, 6 ],
                 'b' : [7, 8, 9, 9],
                 'c' : [6, 9, 12, 12]},
                index = pd.MultiIndex.from_tuples(
                                    [('d', 1), ('d',2), ('e', 2), ('e', 3)],
                                    names = ['n', 'v']    )
                                )
df
Out[6]:
a b c
n v
d 1 4 7 6
2 5 8 9
e 2 6 9 12
3 6 9 12
In [7]:
# drop_duplicates을 수행하면 중복된 행을 제거해준다
df.drop_duplicates()
Out[7]:
a b c
n v
d 1 4 7 6
2 5 8 9
e 2 6 9 12
In [8]:
# 하지만 위의 코드를 실행 후 다시 데이터프레임을 불러오면 중복된 값이 그대로 살아있다.
df
Out[8]:
a b c
n v
d 1 4 7 6
2 5 8 9
e 2 6 9 12
3 6 9 12
In [9]:
# 결과를 데이터프레임에 적용하려면 아래와 같이 괄호 안에 inplace = True 추가하면 된다.
# df.drop_duplicates(inplace=True)

# 하지만 권장되는 방법은 아니며 주로 아래와 같이 기존 데이터 프레임에 덧씌우는 방식을 사용
df = df.drop_duplicates()
In [10]:
# 중복데이터가 제거된체 데이터프레임이 저장되었음을 확인할 수 있다.
df
Out[10]:
a b c
n v
d 1 4 7 6
2 5 8 9
e 2 6 9 12

Logic in 파이썬(판다스)

연산자 의미 연산자 의미
< Less than != Not equal to
> Greater than df['column명'].isin(values) value값을 포함하는지의 여부
== equal pd.isnull(obj) Null값 여부
<= Less than or equals pd.notnull(obj) Not Null 여부
>= Greater than or equals &, I , ~, ^, any( ) , df.all( ) and, or, not, xor, any, all
In [11]:
# 예시데이터 불러오기
import numpy as np

df = pd.DataFrame(
                {'a' : [4, 5, 6, 6, np.nan ],
                 'b' : [7, 8, 9, 9, np.nan],
                 'c' : [6, 9, 12, np.nan, 12]},
                index = pd.MultiIndex.from_tuples(
                                    [('d', 1), ('d',2), ('e', 2), ('e', 3), ('e', 4)],
                                    names = ['n', 'v']    )
                                )
df
Out[11]:
a b c
n v
d 1 4.0 7.0 6.0
2 5.0 8.0 9.0
e 2 6.0 9.0 12.0
3 6.0 9.0 NaN
4 NaN NaN 12.0

예시를 이용해서 로직 하나씩 실행해보기

In [12]:
df['a'] < 5
Out[12]:
n  v
d  1     True
   2    False
e  2    False
   3    False
   4    False
Name: a, dtype: bool
In [13]:
df['b'] != 7
Out[13]:
n  v
d  1    False
   2     True
e  2     True
   3     True
   4     True
Name: b, dtype: bool
In [14]:
df['a'] == 5
Out[14]:
n  v
d  1    False
   2     True
e  2    False
   3    False
   4    False
Name: a, dtype: bool
In [15]:
df['a'].isin([5])
Out[15]:
n  v
d  1    False
   2     True
e  2    False
   3    False
   4    False
Name: a, dtype: bool
In [16]:
pd.isnull(df)
Out[16]:
a b c
n v
d 1 False False False
2 False False False
e 2 False False False
3 False False True
4 True True False
In [17]:
# isnull() 과 sum() 을 같이 활용해서 null 값의 수를 셀 수 있다.
df['a'].isnull().sum()
Out[17]:
1
In [18]:
pd.notnull(df)
Out[18]:
a b c
n v
d 1 True True True
2 True True True
e 2 True True True
3 True True False
4 False False True
In [19]:
# isnull() 과 any()를 동시에 사용해서 null 값이 하나라도 있으면 True를 반환
df.isnull().any()
Out[19]:
a    True
b    True
c    True
dtype: bool
In [20]:
# isnull() 과 all()를 동시에 사용해서 모두 null 값이면 True를 반환
df.isnull().all()
Out[20]:
a    False
b    False
c    False
dtype: bool
In [21]:
# ~ 는 not 의 의미로 아래에서는 결국 Null이면 True를 반환
~df['a'].notnull()
Out[21]:
n  v
d  1    False
   2    False
e  2    False
   3    False
   4     True
Name: a, dtype: bool
In [22]:
# 데이터프레임에서는 and를 쓸 수 없고 & 를 사용해야함
df[(df['b']==7) and (df['a'] ==4) ]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-6decfb4c32c4> in <module>
      1 # 데이터프레임에서는 and를 쓸 수 없고 & 를 사용해야함
----> 2 df[(df['b']==7) and (df['a'] ==4) ]

/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1476         raise ValueError("The truth value of a {0} is ambiguous. "
   1477                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1478                          .format(self.__class__.__name__))
   1479 
   1480     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
In [23]:
df[ (df['b']==7) & (df['a'] ==4) ]
Out[23]:
a b c
n v
d 1 4.0 7.0 6.0

데이터프레임의 일부샘플 조회하기

df.head( ) 와 df.tail( ) 을 이용한 조회

In [24]:
# 최초 n행 조회하기 (default는 5행)
df.head(2)
Out[24]:
a b c
n v
d 1 4.0 7.0 6.0
2 5.0 8.0 9.0
In [25]:
# 마지막 n행 조회하기 (default는 5행)
df.tail(2)
Out[25]:
a b c
n v
e 3 6.0 9.0 NaN
4 NaN NaN 12.0

df.sample( ) 을 이용한 샘플 추출

In [26]:
# 전체 데이터프레임에서 특정 비율만큼 샘플링하는 것
df.sample(frac=0.5) 
Out[26]:
a b c
n v
e 2 6.0 9.0 12.0
d 1 4.0 7.0 6.0
In [27]:
# 하지만 코드를 실행할 때마다 다른 샘플이 나옴
df.sample(frac=0.5) 
Out[27]:
a b c
n v
e 3 6.0 9.0 NaN
d 1 4.0 7.0 6.0
In [28]:
# 아래와 같이 난수값을 설정함으로써 일관된 샘플을 할 수 있다.
df.sample(frac=0.5, random_state=5) 
Out[28]:
a b c
n v
e 4 NaN NaN 12.0
d 1 4.0 7.0 6.0
In [29]:
# 샘플 갯수 설정
df.sample(n=3)
Out[29]:
a b c
n v
e 2 6.0 9.0 12.0
3 6.0 9.0 NaN
d 1 4.0 7.0 6.0

df.iloc[ ]와 콜론(:)을 이용한 데이터프레임 조회

In [30]:
# df.iloc[인덱스 시작: 인덱스 끝]
# iloc로 조회를 할 떄 인덱스 끝의 바로 앞 데이터까지만 조회가 된다.
df.iloc[2:4]  
Out[30]:
a b c
n v
e 2 6.0 9.0 12.0
3 6.0 9.0 NaN
In [31]:
# 콜론 앞에 아무것도 입력하지 않으면 첫 데이터부터 조회
df.iloc[:4]
Out[31]:
a b c
n v
d 1 4.0 7.0 6.0
2 5.0 8.0 9.0
e 2 6.0 9.0 12.0
3 6.0 9.0 NaN
In [32]:
# 음수값을 입력하면 뒤에서 몇번째인지를 나타냄
# 아래 코드는 뒤에서 두번째 행부터 끝까지 조회
df.iloc[-2:]
Out[32]:
a b c
n v
e 3 6.0 9.0 NaN
4 NaN NaN 12.0
In [33]:
# df.iloc 
df.iloc[2:4, 1:]
Out[33]:
b c
n v
e 2 9.0 12.0
3 9.0 NaN

df.nlargest( ) 과 df.nsmallest( )

In [34]:
# 샘플 데이터프레임 생성
df = pd.DataFrame(  { 'a' : [1, 10, 8, 11, -1],
                             'b' : list('abcde'),
                             'c' : [1.0, 2.0, np.nan, 3.0, 4.0]}  )
df
Out[34]:
a b c
0 1 a 1.0
1 10 b 2.0
2 8 c NaN
3 11 d 3.0
4 -1 e 4.0
In [35]:
# 가장 큰  a 값을 가진 행 조회
df.nlargest(1, 'a')
Out[35]:
a b c
3 11 d 3.0
In [36]:
#  a 값이 큰 순서대로 상위 3개 행 조회
df.nlargest(3, 'a')
Out[36]:
a b c
3 11 d 3.0
1 10 b 2.0
2 8 c NaN
In [37]:
# 문자열에는 사용할 수 없음
df.nlargest(2, 'b')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-b38daf335006> in <module>
      1 # 문자열에는 사용할 수 없음
----> 2 df.nlargest(2, 'b')

/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in nlargest(self, n, columns, keep)
   4909                                        n=n,
   4910                                        keep=keep,
-> 4911                                        columns=columns).nlargest()
   4912 
   4913     def nsmallest(self, n, columns, keep='first'):

/anaconda3/lib/python3.7/site-packages/pandas/core/algorithms.py in nlargest(self)
   1056 
   1057     def nlargest(self):
-> 1058         return self.compute('nlargest')
   1059 
   1060     def nsmallest(self):

/anaconda3/lib/python3.7/site-packages/pandas/core/algorithms.py in compute(self, method)
   1172                     "Column {column!r} has dtype {dtype}, cannot use method "
   1173                     "{method!r} with this dtype"
-> 1174                 ).format(column=column, dtype=dtype, method=method))
   1175 
   1176         def get_indexer(current_indexer, other_indexer):

TypeError: Column 'b' has dtype object, cannot use method 'nlargest' with this dtype
In [38]:
#  a 값이 작은 순서대로 상위 3개 행 조회
df.nsmallest(3, 'a')
Out[38]:
a b c
4 -1 e 4.0
0 1 a 1.0
2 8 c NaN
1. Creating DataFrames (데이터 프레임 만들기)
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))

딕셔너리를 사용하여 DataFrame 생성하기

In [2]:
import pandas as pd
In [3]:
# 인덱스 옵션을 넣지 않으면 행 인덱스가 0부터 생성
df = pd.DataFrame(
                {'a' : [4, 5, 6],
                 'b' : [7, 8, 9],
                 'c' : [10, 11, 12]},
                )

df
Out[3]:
a b c
0 4 7 10
1 5 8 11
2 6 9 12
In [4]:
# 인덱스 값을 입력해서 내가 원하는 임의의 인덱스 값을 설정할 수 있다.
df = pd.DataFrame(
                {'a' : [4, 5, 6],
                 'b' : [7, 8, 9],
                 'c' : [10, 11, 12]},
                 index = [1, 2, 3]
                )

df
Out[4]:
a b c
1 4 7 10
2 5 8 11
3 6 9 12

데이터 프레임에서 특정 데이터 불러오기

In [5]:
# 하나의 컬럼만 불러오기
df['a']
Out[5]:
1    4
2    5
3    6
Name: a, dtype: int64
In [6]:
# 두 개 이상의 컬럼을 불러올 때는 대괄호 안에 리스트 형식으로 불러온다.
df[ ['a','b'] ]
Out[6]:
a b
1 4 7
2 5 8
3 6 9
In [7]:
# 행(혹은 인덱스) 기준으로 데이터를 불러올 때는 df.loc[인덱스] 를 사용
df.loc[2]
Out[7]:
a     5
b     8
c    11
Name: 2, dtype: int64
In [8]:
# df.loc[인덱스, 컬럼명] 을 사용해서 특정 행, 열의 데이터를 불러올 수 있다
df.loc[2, 'a']
Out[8]:
5
In [9]:
# 이 때 복수의 행과 열을 조회할 때는 행과 열을 각각 리스트 형식으로 적어주면 된다
df.loc[[1, 2], ['a', 'b']]
Out[9]:
a b
1 4 7
2 5 8

리스트를 사용해서 컬럼명 만들기

In [10]:
# 리스트를 사용하여 데이터프레임을 만들 때, 컬럼명 옵션을 입력하지 않으면
# 0부터 순서대로 컬럼명이 만들어진다
df = pd.DataFrame(
                [ [4, 5, 6],
                  [7, 8, 9],
                  [10, 11, 12]],
                index = [1, 2, 3]
                )

df
Out[10]:
0 1 2
1 4 5 6
2 7 8 9
3 10 11 12
In [11]:
# 때문에 리스트로 데이터 프레임을 만들 때 아래 처럼 컬럼명을 설정해주는 것이 보통
df = pd.DataFrame(
                [ [4, 5, 6],
                  [7, 8, 9],
                  [10, 11, 12]],
                 index = [1, 2, 3],
                columns = ['a', 'b', 'c']
                )

df
Out[11]:
a b c
1 4 5 6
2 7 8 9
3 10 11 12

데이터프레임 만들기 : Multi Index

In [12]:
# 복수의 인덱스를 만들어 줄 수도 있음 (pd.Multiindex 사용)
df = pd.DataFrame(
                            {'a' : [4, 5, 6], 
                             'b' : [7, 8, 9],
                             'c' : [6, 9, 12]},
                            index = pd.MultiIndex.from_tuples( [('d', 1), ('d', 2), ('e', 2)] ,
                                                                                     names = ['n', 'v'] )
                                )

df
Out[12]:
a b c
n v
d 1 4 7 6
2 5 8 9
e 2 6 9 12

+ Recent posts