Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas CategoricalIndex - จัดลำดับหมวดหมู่ใหม่


หากต้องการเรียงลำดับหมวดหมู่ ให้ใช้ CategoricalIndex reorder_categories() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import pandas as pd

CategoricalIndex ใช้ได้กับค่าที่เป็นไปได้จำกัดและมักจะคงที่เท่านั้น ตั้งค่าหมวดหมู่สำหรับหมวดหมู่โดยใช้พารามิเตอร์ "หมวดหมู่" ปฏิบัติต่อการจัดหมวดหมู่ตามคำสั่งโดยใช้พารามิเตอร์ "จัดลำดับ" -

catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

แสดงดัชนีหมวดหมู่ -

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')