परिचय
पैंडास इंडेक्स में उन मानों को बदलने के लिए जहां शर्त गलत (False) हो, index.where() मेथड का उपयोग index.isin() के साथ करें।
आवश्यक लाइब्रेरी आयात करें
import pandas as pd
पैंडास इंडेक्स बनाएं
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
पैंडास इंडेक्स प्रदर्शित करें
print("पैंडास इंडेक्स...\n", index)
जहां शर्त गलत हो वहां मान बदलें
यहां, 'Decor' को छोड़कर हर दूसरे तत्व को बदल दिया जाता है।
print("\nजहां शर्त गलत हो वहां इंडेक्स मान बदलें...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))
पूर्ण उदाहरण
import pandas as pd
# पैंडास इंडेक्स बनाएं
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
# पैंडास इंडेक्स प्रदर्शित करें
print("पैंडास इंडेक्स...\n", index)
# इंडेक्स में तत्वों की संख्या लौटाएं
print("\nइंडेक्स में तत्वों की संख्या...\n", index.size)
# डेटा का dtype लौटाएं
print("\nDtype ऑब्जेक्ट...\n", index.dtype)
# जहां शर्त गलत हो वहां मान बदलें
# यहां, 'Decor' को छोड़कर हर दूसरा तत्व बदल जाता है
print("\nजहां शर्त गलत हो वहां इंडेक्स मान बदलें...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))
आउटपुट
पैंडास इंडेक्स... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products') इंडेक्स में तत्वों की संख्या... 5 Dtype ऑब्जेक्ट... object जहां शर्त गलत हो वहां इंडेक्स मान बदलें... Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous', 'Miscellaneous'], dtype='object', name='Products')
व्याख्या
index.isin(['Decor'])बूलियन मास्क बनाता है: केवल 'Decor' के लिए True।where(cond, other)जहां कंडीशन True है, मूल मान रखता है; जहां False,otherसे बदल देता है।- परिणाम: केवल 'Decor' मूल रहता है, बाकी 'Miscellaneous' हो जाते हैं।
- नाम 'Products' संरक्षित रहता है।