その先にあるもの…

[PYTHON] DataFrame 인덱스 설정( set_index, reset_index ) 본문

프로그래밍/Python

[PYTHON] DataFrame 인덱스 설정( set_index, reset_index )

specialJ 2020. 6. 4. 17:49

df = pd.DataFrame( [[1,2,3], [4,5,6], [7,8,9] ], index= ["row1", "row2", "row3"], columns=['col1', 'col2', 'col3'] )

 

      col1  col2  col3
row1     1     2     3
row2     4     5     6
row3     7     8     9
Index(['row1', 'row2', 'row3'], dtype='object')

 

 

 

// 'col3'을 새로운 인덱스로 선택한다.

df1 = df.set_index( 'col3')

 

          col1  col2
col3
3        1        2
6        4        5
9        7        8
Int64Index([3, 6, 9], dtype='int64', name='col3')

 

 

// 인덱스 reset

// 기존의 인덱스는 새로운 열에 추가된다.

// 인덱스가 정수로 변경

df2 = df1.reset_index( )

 

   col3  col1  col2
0     3     1     2
1     6     4     5
2     9     7     8
RangeIndex(start=0, stop=3, step=1)

 

 

//drop = true 기존의 인덱스를 삭제한다. 'col3'이 삭제되었다.

//inplace=true 새로운 데이터로 덮어씌운다. df2로 카피하지 않는다.

df1.reset_index( drop=True, inplace=True )

   col1  col2
0     1     2
1     4     5
2     7     8
RangeIndex(start=0, stop=3, step=1)

Comments