[Python] pandas library DataFrame .loc vs .iloc
.loc
- .loc: is primarily label based
- 주로 "레이블"과 관련된 처리를 하며 부울 타입의 배열(데이터)도 처리가 가능
DataFrame .loc 예시
딕셔너리 형태의 DataFrame 생성하기
아래 코드 결과와 같이 DataFrame(2차원 이상) 형태로 반환하고 싶은 경우 [[]]로 처리
첫번째 코드는 column을 지정하지 않고 row(행)만 선택한 예시이다
column을 지정하지 않았으므로 모든 칼럼이 선택된 것을 확인할 수 있다
두번째 코드는 row('E', 'F')와 column('team', 'assists')을 모두 지정하여 선택한 예시이다
세번째 코드는 slicing(슬라이싱)을 사용하여 row와 column을 선택한 예시이다
numpy array와 시퀀스 타입의 슬라이싱과 동일한 로직임을 확인할 수 있다
- 위 사진에서 설명하는 것을 유의깊게 봐야 한다.
- python의 슬라이싱의 경우 마지막 stop의 전 까지만 데이터를 가져옴
- 반면, .loc의 경우 stop을 포함한다.
아래 코드를 보면 리스트의 슬라이싱은 stop을 포함하지 않으며, DataFrame의 .loc의 경우 stop을 포함하는 것을 알 수 있다.
.iloc
- .iloc: is primarily integer position based
- .iloc는 '정수 위치 기반(integer-location based)' 인덱싱을 제공하며, 이를 통해 DataFrame의 행과 열을 정수 인덱스를 사용하여 접근할 수 있다.
- 부울 타입의 배열(데이터)도 처리가 가능
- 이 기능은 Python의 기본적인 리스트 슬라이싱과 유사하게 동작
- 주의 사항
- .iloc은 정수 인덱스만 사용하므로, 열 또는 행의 이름을 사용하여 접근할 수 없음
- 이름을 사용하려면 .loc 인덱서를 사용해야 한다.
- Python의 일반적인 인덱싱 규칙을 따름
- 즉, 시작 인덱스는 포함되지만, 끝 인덱스는 포함되지 않음
- .iloc은 정수 인덱스만 사용하므로, 열 또는 행의 이름을 사용하여 접근할 수 없음
DataFrame .iloc 예시
딕셔너리 형태의 DataFrame 생성하기
주의사항에서 언급했듯이 python의 슬라이싱과 유사하므로 stop을 포함하지 않는다 !
틀린 부분 댓글로 작성해주시면 감사하겠습니다 😊
Reference
- https://www.statology.org/pandas-loc-vs-iloc/https://stackoverflow.com/questions/54718821/python-pandas-does-loc-and-iloc-stand-for-anything
- https://stackoverflow.com/questions/54718821/python-pandas-does-loc-and-iloc-stand-for-anything
- https://vamos00.notion.site/6-pandas-ab452cea54e4491a8a3806c1e734d080?pvs=4
- 학과에서 공부한 내용을 간략하게 정리해놓은 노션 자료 입니다. 도움이 되셨으면 좋겠습니다 :)
- https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html#pandas.DataFrame.loc
- https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html#pandas.DataFrame.iloc
pandas.DataFrame.iloc — pandas 2.1.4 documentation
A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your sel
pandas.pydata.org
pandas.DataFrame.loc — pandas 2.1.4 documentation
A slice object with labels, e.g. 'a':'f'. Warning Note that contrary to usual python slices, both the start and the stop are included
pandas.pydata.org
6주차 - pandas | Built with Notion
수업 목표
vamos00.notion.site
Python Pandas: Does 'loc' and 'iloc' stand for anything?
I've been using pandas for a while now, I understand what loc and iloc do. But till this day I don't know if these two things stand for something? Are they short for something or abbreviations? Or...
stackoverflow.com
Pandas loc vs. iloc: What's the Difference? - Statology
This tutorial explains the difference between loc and iloc in pandas, including several examples.
www.statology.org