인덱스 

 

판다스에서 인덱스는 없어서는 안될 필수적인 요소이다. 

파일을 로딩해서 .index 매서드를 통해서 인덱스를 가져올 수 있다. 
이 때, 1차원 array 형태가 반환되고, ndarray처럼 단일 값을 반환하거나, 슬라이싱 하는 것도 가능하다. 

 

import pandas as pd
import numpy as np


#원본 파일 다시 로딩 
titnaic_df = pd.read_csv('titanic_train.csv')
#Index 객체 추출 
indexes = titanic_df.index
print(indexes)
#Index 객체를 실제 값 array로 변환 
print('Index 객체 array 값 : \n', indexes.values)

 

 

 

print(type(indexes.values))
print(indexes.values.shape)
print(indexes[:5].values)
print(indexes.values[:5])
print(indexes[6])

 

하지만, DataFrame, Series의 Index 객체는 함부로 변경할 수 없다. 또한, Series 객체에 연산 함수를 적용할 때, Index는 연산에서 제외된다. Index(인덱스)는 오직 식별용으로만 사용한다.

 

indexes[0] = 5

 

 

 

 


 

 

 

.reset_index()

 

위 매서드는 새롭게 인덱스를 연속 숫자형으로 할당하고, 기존의 인덱스는 'index'라는 새로운 열을 만들어 추가한다. 이 때, Seires에 reset_index()를 적용하면 DataFrame이 되는 것에 유의하자.

인덱스가 연속된 int 숫자형 데이터가 아닌 경우에 다시 이를 연속 int 숫자형 데이터로 만들 때 주로 사용한다. 

reset_index()의 파라미터 중 'drop = True'로 하면 index 칼럼이 추가되지 않는다. 

 

 

titanic_reset_df = titanic_df.reset_index(inplace = False)
titanic_reset_df.head(3)

 

 

 

reset_index()에서 주의할 점은 Series에 .reset_index() 매서드를 사용하는 경우 DataFrame 형태로 변환된다는 것을 인지해야 한다. 혹은 'drop = True' 설정을 통해서 별도의 index 열을 만들지 않는 경우에는 Series 형태가 그대로 유지된다. 

 

 

print('### before reset_index ###')
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
print('value_counts 객체 변수 타입 : ', type(value_counts))
new_value_counts = value_counts.reset_index(inplace = False)
print('### After reset_index ###')
print(new_value_counts)
print('new_value_counts 객체 변수 타입 :', type(new_value_counts))

 

728x90
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 라이프코리아트위터 공유하기
  • shared
  • 카카오스토리 공유하기