Pandas에서 인덱스를 열로 변환하는 방법(예제 포함)
다음 기본 구문을 사용하여 Pandas DataFrame의 인덱스를 열로 변환할 수 있습니다.
#convert index to column df. reset_index (inplace= True )
Pandas MultiIndex DataFrame이 있는 경우 다음 구문을 사용하여 특정 인덱스 수준을 열로 변환할 수 있습니다.
#convert specific level of MultiIndex to column df. reset_index (inplace= True ,level=[' Level1 '])
다음 예에서는 이 구문을 실제로 사용하는 방법을 보여줍니다.
예 1: 인덱스를 열로 변환
다음 코드는 Pandas DataFrame의 인덱스를 열로 변환하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19], ' assists ': [5, 7, 7, 9, 12], ' rebounds ': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 #convert index to column df. reset_index (inplace= True ) #view updated DataFrame df index points assists rebounds 0 0 25 5 11 1 1 12 7 8 2 2 15 7 10 3 3 14 9 6 4 4 19 12 6
예 2: MultiIndex를 열로 변환
다음과 같은 팬더 MultiIndex DataFrame이 있다고 가정합니다.
import pandas as pd #createDataFrame index_names = pd. MultiIndex . from_tuples ([('Level1','Lev1', 'L1'), ('Level2','Lev2', 'L2'), ('Level3','Lev3', 'L3'), ('Level4','Lev4', 'L4')], names=['Full','Partial', 'ID']) data = {' Store ': ['A','B','C','D'], ' Sales ': [17, 22, 29, 35]} df = pd. DataFrame (data, columns = [' Store ',' Sales '], index=index_names) #view DataFrame df Store Sales Full Partial ID Level1 Lev1 L1 A 17 Level2 Lev2 L2 B 22 Level3 Lev3 L3 C 29 Level4 Lev4 L4 D 35
다음 코드는 MultiIndex의 각 수준을 Pandas DataFrame의 열로 변환하는 방법을 보여줍니다.
#convert all levels of index to columns df. reset_index (inplace= True ) #view updated DataFrame df Full Partial ID Store Sales 0 Level1 Lev1 L1 A 17 1 Level2 Lev2 L2 B 22 2 Level3 Lev3 L3 C 29 3 Level4 Lev4 L4 D 35
다음 코드를 사용하여 MultiIndex의 특정 수준만 열로 변환할 수도 있습니다.
#convert just 'ID' index to column in DataFrame
df. reset_index (inplace= True ,level=[' ID '])
#view updated DataFrame
df
ID Store Sales
Full Partial
Level1 Lev1 L1 A 17
Level2 Lev2 L2 B 22
Level3 Lev3 L3 C 29
Level4 Lev4 L4 D 35
DataFrame에서는 “ID” 수준만 열로 변환되었습니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 기능을 수행하는 방법을 설명합니다.
Pandas에서 열을 인덱스로 설정하는 방법
Pandas에서 인덱스별로 열을 삭제하는 방법
Pandas에서 인덱스와 열을 기준으로 DataFrame을 정렬하는 방법