Skip to content

파이썬 라이브러리 pandas #
Find similar titles

Structured data

Category
Programming

pandas #

iloc, loc, ix의 차이 #

pandas의 DataFrame의 indexing에 사용하는 .iloc, .loc, .ix는 비슷해 보이지만 각각의 용도에 맞게 사용해야한다. 다음은 각각에 대한 설명이다.

  • .iloc
    integer position을 통해서 indexing 할 수 있다.

  • .loc
    label을 통해 indexing 할 수 있다.

  • .ix
    integer position과 label 모두 사용할 수 있다. 만약 label이 숫자라면 label-based indexing이 된다.

예를들어, 다음과 같이 label이 숫자로 이루어진 Series가 있다면,

>>> s = pd.Series(np.nan, index=[49,48,47,46,45, 1, 2, 3, 4, 5])
>>> s
49   NaN
48   NaN
47   NaN
46   NaN
45   NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN

s.iloc[:3]은 integer position을 이용하므로 1-3번 rows를 반환할 것이고, s.loc[:3]은 label을 이용하므로 1-8번 rows를 반환할 것이다. s.ix[:3]은 label이 숫자인 경우 label-based indexing을 따르므로 .loc처럼 1-8번째 rows를 반환할 것이다.

하지만, 만일 label이 아래와 같이 숫자와 문자로 (mixed label 이라 함) 이루어져 있다면,

>>> s2 = pd.Series(np.nan, index=['a','b','c','d','e', 1, 2, 3, 4, 5])
>>> s2.index.is_mixed() # index is mix of types
True
>>> s2.ix[:6] # behaves like iloc given integer
a   NaN
b   NaN
c   NaN
d   NaN
e   NaN
1   NaN

s2.ix[:6]는 에러를 내지 않고 .iloc처럼 1-6번 row를 반환한다. 또한 s2.ix[:'c']를 하면 .loc처럼 1-3번 rows를 반환한다.

label과 integer position 중 하나만 이용하고자 한다면 .iloc이나 .loc을 사용하면 된다. 하지만 두 방법을 섞어서 쓰고 싶다면 .ix를 이용해야한다. 예를 들면 다음과 같다.

>>> df = pd.DataFrame(np.arange(16).reshape(4,4),
                      index=list('ABCD'), columns=['a', 'b', 1, 2])
    a   b   1   2
A   0   1   2   3
B   4   5   6   7
C   8   9  10  11
D  12  13  14  15

mixed index를 사용하고 있는 DataFrame, df의 'c'줄(label), 4번째 (integer position) 까지만 slicing하고자 한다면 .ix를 통해 다음과 같이 할 수 있다.

>>> df.ix[:'C', :3]
   a  b   1
A  0  1   2
B  4  5   6
C  8  9  10

Incoming Links #

Related Data Sciences #

Related Articles #

Suggested Pages #

0.0.1_20210630_7_v33