인덱스 설정

Published by onesixx on

https://kongdols-room.tistory.com/123

set_index, reset_index

직접 Index 지정

DataFrame의 index 및 columns 어트리뷰트에 대한 직접 배정

df.index = 대입

import pandas as pd
import numpy as np

ex_df = pd.DataFrame(np.arange(0,9).reshape(3,3))
# \t0\t1\t2
# 0\t0\t1\t2
# 1\t3\t4\t5
# 2\t6\t7\t8


ex_df.index
# RangeIndex(start=0, stop=3, step=1)
ex_df.index = ['i0', 'i1', 'i2']
# Index(['i0', 'i1', 'i2'], dtype='object')

# \t    0\t1\t2
# i0\t0\t1\t2
# i1\t3\t4\t5
# i2\t6\t7\t8


ex_df.columns
# RangeIndex(start=0, stop=3, step=1)
ex_df.columns = [ 'col0', 'col2', 'col3']
# Index(['col0', 'col2', 'col3'], dtype='object')

# \t col0\t col2\t col3
# i0\t0\t    1\t    2
# i1\t3\t    4\t    5
# i2\t6\t    7   \t8

set_index( 컬럼)

DataFrame내의 열을 이용한 인덱스 설정

DataFrame.set_index(keys, drop=True, append=False, inplace=False)

  • drop: 인덱스에 활용된 해당열을 삭제 여부
  • append: 기존인덱스를 삭제여부
  • inplace: 원본 dataframe객체를 덮어쓸건지 여부 (True이면 바뀐 인덱스를 가진 데이터만 남는다)
import pandas as pd
import numpy as np

ex_df = pd.DataFrame(
    np.arange(0,9).reshape(3,3), 
    index = ['i0', 'i1', 'i2'],
    columns = [ 'col0', 'col2', 'col3']
)
# \t col0\t col2\t col3
# i0\t0\t    1\t    2
# i1\t3\t    4\t    5
# i2\t6\t    7   \t8

ex_df.set_index('col2')
# \t    col0\tcol3
# col2\t\t
#   1\t   0\t   2
#   4\t   3       5
#   7\t   6\t   8

여기서 상식적이지않지만, index는 중복이 가능하다. (Primary key가 아니다)

인덱스 초기화

reset_index()

set_index()와 반대로 작용하여, 인덱스를 리셋할때 사용.
(즉, 현재 Index를 column으로 만들고, index값을 정수인덱스로 만듦)
의 기능을 역으로 수행한다.

DataFrame.reset_index(drop=False, inplace=False)

# \t col0\t col2\t col3
# i0\t0\t    1\t    2
# i1\t3\t    4\t    5
# i2\t6\t    7   \t8

ex_df.reset_index()
ex_df.reset_index(level=[0])
#      index\tcol0\tcol2\tcol3
# 0\t      i0\t   0\t   1\t   2
# 1\t      i1\t   3\t   4\t   5
# 2\t      i2\t   6\t   7\t   8

multi Index

exam.reset_index(drop=False, inplace=True)
exam.set_index(["class", "name"], inplace = True)

#               col2
# col0\tcol3
# 0\t    2\t    1
# 3\t    5\t    4
# 6\t    8\t    7


exam.index
# MultiIndex([(0, 2),
#             (3, 5),
#             (6, 8)],
#            names=['col0', 'col3'])

ex_df.reset_index()

sort_index

exam.sort_index(inplace=True)
exam


ETC

Categories: pandas

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x