หากต้องการแทนที่ค่าดัชนีที่มีเงื่อนไขเป็นเท็จ ให้ใช้ index.isin() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
การสร้างดัชนีนุ่น -
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')
แสดงดัชนีหมีแพนด้า −
print("Pandas Index...\n",index) แทนที่ค่าที่เงื่อนไขเป็นเท็จ ที่นี่ ยกเว้น 'การตกแต่ง' องค์ประกอบอื่น ๆ ทั้งหมดจะถูกแทนที่ -
print("\nReplace index vales where condition is False...\n",index.where(index.isin(['Decor']), 'Miscellaneous')) ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd
# Creating Pandas index
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)
# replace values where condition is False
# Here, except the 'Decor', every other element gets replaced
print("\nReplace index vales where condition is False...\n",index.where(index.isin(['Decor']), 'Miscellaneous')) ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products') Number of elements in the index... 5 The dtype object... object Replace index vales where condition is False... Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous','Miscellaneous'],dtype='object', name='Products')