ในการรับรหัสหมวดหมู่ของหมวดหมู่นี้ ให้ใช้ รหัส คุณสมบัติของ ดัชนีหมวดหมู่ ในหมีแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
CategoricalIndex สามารถใช้กับค่าที่เป็นไปได้ (หมวดหมู่) ที่จำกัดและมักจะคงที่เท่านั้น ตั้งค่าหมวดหมู่สำหรับหมวดหมู่โดยใช้พารามิเตอร์ "หมวดหมู่" จัดหมวดหมู่ตามคำสั่งโดยใช้พารามิเตอร์ "สั่งซื้อ" รหัสคืออาร์เรย์ของจำนวนเต็มซึ่งเป็นตำแหน่งของค่าจริงในอาร์เรย์ประเภท -
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
แสดงดัชนีหมวดหมู่ -
print("Categorical Index...\n",catIndex)
รับรหัสหมวดหมู่ -
print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd # CategoricalIndex can only take on a limited, and usually fixed, number of possible values # Set the categories for the categorical using the "categories" parameter # Treat the categorical as ordered using the "ordered" parameter # Codes are an array of integers which are the positions of the actual values in the categories array. catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"]) # Display the Categorical Index print("Categorical Index...\n",catIndex) # Get the categories print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories) # Get the category codes print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
Categorical Index... 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') Category codes from CategoricalIndex... [0 1 2 3 0 1 2 3]