카테고리를 정렬하려면 CategoricalIndex reorder_categories()를 사용하세요. Pandas의 메소드. 먼저 필요한 라이브러리를 가져옵니다 -
import pandas as pd
CategoricalIndex는 가능한 값의 제한적이고 일반적으로 고정된 수만 취할 수 있습니다. "categories" 매개변수를 사용하여 범주에 대한 범주를 설정합니다. "ordered" 매개변수를 사용하여 범주형을 정렬된 것으로 취급하십시오 -
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
CategoricalIndex 표시 -
print("CategoricalIndex...\n",catIndex)
카테고리 가져오기 -
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories) reorder_categories()를 사용하여 범주를 재정렬합니다. 새로운 순서로 카테고리를 매개변수로 설정 -
print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"])) 예
다음은 코드입니다 -
import pandas as pd
# CategoricalIndex can only take on a limited,and usually fixed, number of possible values (categories
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
# Display the CategoricalIndex
print("CategoricalIndex...\n",catIndex)
# Get the categories
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)
# Reorder categories using reorder_categories()
# Set the categories in new order as a parameter
print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"])) 출력
이것은 다음과 같은 출력을 생성합니다 -
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') DisplayingCategories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex after reordering categories... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')