새 카테고리를 추가하려면 CategoricalIndex add_categories()를 사용하세요. Pandas의 메소드. 먼저 필요한 라이브러리를 가져옵니다 -
import pandas as pd
"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)
add_categories()를 사용하여 새 범주를 추가합니다. 새 범주를 매개변수로 설정합니다. 새 카테고리는 카테고리의 마지막/가장 높은 위치에 포함됩니다 -
print("\nCategoricalIndex after adding new categories...\n",catIndex.add_categories(["a", "b", "c", "d"])) 예시
다음은 코드입니다 -
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)
# Add new categories using add_categories()
# Set the new categories as a parameter
# The new categories will be included at the last/highest place in the categories
print("\nCategoricalIndex after adding new categories...\n",catIndex.add_categories(["a", "b", "c", "d"])) 출력
이것은 다음과 같은 출력을 생성합니다 -
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 adding new categories... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's', 'a', 'b', 'c', 'd'], ordered=True, dtype='category')