Computer/Python
[Python/Pandas] loc 과 iloc 은 다르게 반응한다?
pleasebetrue
2018. 12. 12. 00:15
loc 과 iloc 은 pandas DataFrame에서 정확한 행/열 을 가져올 때 많이 사용한다.
하지만 이 둘의 index 처리법이 다소 다르다.
아래를 보자.
df.iloc[1:3, 0]
1 Afghanistan 2 Afghanistan Name: country, dtype: object
iloc 은 1:3 의 행동이 numpy.arange(1, 3) 과 비슷하다. 즉 1 과 2만 값으로 들어가는 것이다.
이에 반해 loc은 index에 1:3 을 하게 되면 1, 2, 3 의 값으로 인식한다.
df.loc[1:3, 'country']
1 Afghanistan 2 Afghanistan 3 Afghanistan Name: country, dtype: object
iloc을 쓸 때 ! 꼭 유의하자.
p.s. ix는 이제 사용하지 않으니 유의하자.
만약 꼭 label 과 index 를 섞어서 해야 한다면, df.columns[n] 을 사용해보자.