Để đặt các danh mục của CategoricalIndex được sắp xếp, hãy sử dụng as_ordered () trong Pandas.
Đầu tiên, hãy nhập các thư viện được yêu cầu -
import pandas as pd
Đặt danh mục cho danh mục bằng cách sử dụng thông số "danh mục" -
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])
Nhận các danh mục -
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)
Đặt các danh mục được sắp xếp -
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered()) Ví dụ
Sau đây là mã -
import pandas as pd
# Set the categories for the categorical using the "categories" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])
# Display the CategoricalIndex
print("CategoricalIndex...\n",catIndex)
# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)
# Set the categories to be ordered
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered()) Đầu ra
Điều này sẽ tạo ra kết quả sau -
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category') Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex ordered... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')