परिचय
मूल इंडेक्स और उसके नाम दोनों को संरक्षित करते हुए DataFrame बनाने के लिए index.to_frame() मेथड का उपयोग करें (डिफ़ॉल्ट व्यवहार)।
आवश्यक लाइब्रेरी आयात करें
import pandas as pd
पैंडास इंडेक्स बनाएं
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
पैंडास इंडेक्स प्रदर्शित करें
print("पैंडास इंडेक्स...\n", index)
DataFrame में बदलें
print("\nइंडेक्स से DataFrame...\n", index.to_frame())
पूर्ण उदाहरण
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)
# इंडेक्स को DataFrame में बदलें
print("\nइंडेक्स से DataFrame...\n", index.to_frame())
आउटपुट
पैंडास इंडेक्स... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
इंडेक्स में तत्वों की संख्या... 5
Dtype ऑब्जेक्ट... object
इंडेक्स से DataFrame...
Products
Products
Electronics Electronics
Accessories Accessories
Decor Decor
Books Books
Toys Toys
व्याख्या
- डिफ़ॉल्ट
index.to_frame()मूल इंडेक्स को DataFrame के इंडेक्स के रूप में रखता है। - कॉलम नाम भी इंडेक्स का नाम ('Products') होता है।
- परिणाम: इंडेक्स और कॉलम दोनों में समान मान होते हैं।
- यह इंडेक्स को डेटा के रूप में निर्यात करने के लिए उपयोगी है।