소개
이 튜토리얼에서는 Python pandas 의 DataFrame.reindex() 메서드에 대해 알아보겠습니다. 이 메서드를 사용하여 DataFrame 의 인덱스와 열을 변경하는 방법을 살펴볼 것입니다. DataFrame.reindex() 메서드를 사용하면 이전 인덱스에 값이 없는 위치에 null 값을 채워 새로운 인덱스와 DataFrame 을 일치시킬 수 있습니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화할 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 즉시 해결해 드리겠습니다.
pandas 라이브러리 가져오기 및 DataFrame 생성
pandas 라이브러리를 가져오고 DataFrame 을 생성하는 것으로 시작해 보겠습니다. 이 DataFrame 을 사용하여 DataFrame.reindex() 메서드를 시연할 것입니다.
import pandas as pd
## Create a DataFrame
df = pd.DataFrame([[1, 6, 2], [3, 4, 6], [12, 1, 0]], columns=['A', 'B', 'C'], index=['index_1', 'index_2', 'index_3'])
index 매개변수를 사용하여 DataFrame 재인덱싱
인덱스를 변경하여 DataFrame 을 재인덱싱하려면, 새로운 인덱스 레이블 목록을 DataFrame.reindex() 메서드에 전달합니다. 원래 DataFrame 에 없는 인덱스 레이블은 NaN 값으로 채워집니다.
## Reindex the DataFrame with a new index
new_index = ['index_1', 'index_2', 'index_4']
reindexed_df = df.reindex(index=new_index)
print(reindexed_df)
Output:
A B C
index_1 1.0 6.0 2.0
index_2 3.0 4.0 6.0
index_4 NaN NaN NaN
columns 매개변수를 사용하여 DataFrame 재인덱싱
마찬가지로, DataFrame.reindex() 메서드를 사용하여 열을 변경하여 DataFrame 을 재인덱싱할 수 있습니다. columns 매개변수에 새로운 열 레이블 목록을 제공합니다. 원래 DataFrame 에 없는 열은 NaN 값으로 채워집니다.
## Reindex the DataFrame with new columns
new_columns = ['A', 'C', 'D']
reindexed_df = df.reindex(columns=new_columns)
print(reindexed_df)
Output:
A C D
index_1 1.0 2.0 NaN
index_2 3.0 6.0 NaN
index_3 12.0 0.0 NaN
fill_value 매개변수를 사용하여 Null 값 채우기
null 값을 특정 값으로 채우려면, DataFrame.reindex() 메서드의 fill_value 매개변수를 사용할 수 있습니다. null 값을 채우는 데 사용할 원하는 값을 제공합니다.
## Reindex the DataFrame and fill null values with 2
new_index = ['index_1', 'index_2', 'index_4']
reindexed_df = df.reindex(index=new_index, fill_value=2)
print(reindexed_df)
Output:
A B C
index_1 1 6 2
index_2 3 4 6
index_4 2 2 2
요약
이 튜토리얼에서는 pandas 에서 DataFrame.reindex() 메서드를 사용하여 DataFrame 을 재인덱싱하는 방법을 배웠습니다. DataFrame 의 인덱스와 열을 변경하고, null 값을 채우고, null 값에 대한 채우기 값을 지정하는 방법을 살펴보았습니다. DataFrame 을 적절하게 재인덱싱하는 방법을 아는 것은 pandas 에서 데이터를 조작하고 정렬하는 데 유용합니다.