ในการตั้งค่าหมวดหมู่ของ CategoricalIndex ให้เป็นแบบไม่เรียงลำดับ ให้ใช้ as_unordered() วิธีการในนุ่น
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
ตั้งค่าหมวดหมู่สำหรับหมวดหมู่โดยใช้พารามิเตอร์ "หมวดหมู่" จัดการหมวดหมู่ตามคำสั่งโดยใช้พารามิเตอร์ "ordered" ด้วยค่า True −
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
ตั้งค่าหมวดหมู่ที่ไม่เรียงลำดับ -
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter with value True
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("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)
# Set the categories to be unordered
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered()) ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex unordered... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category')