Để thay thế các giá trị chỉ mục trong đó điều kiện là Sai, hãy sử dụng index.isin () trong Pandas. Đầu tiên, hãy nhập các thư viện được yêu cầu -
import pandas as pd
Tạo chỉ mục Pandas -
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')
Hiển thị chỉ mục Gấu trúc -
print("Pandas Index...\n",index) Thay thế các giá trị trong đó điều kiện là Sai. Ở đây, ngoại trừ 'Trang trí', mọi thành phần khác đều được thay thế -
print("\nReplace index vales where condition is False...\n",index.where(index.isin(['Decor']), 'Miscellaneous')) Ví dụ
Sau đây là mã -
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')) Đầu ra
Điều này sẽ tạo ra kết quả sau -
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')