एक मल्टीइंडेक्स को लेवल वैल्यू वाले टुपल्स के इंडेक्स में बदलने के लिए, MultiIndex.to_flat_index() का उपयोग करें। विधि।
सबसे पहले, आवश्यक पुस्तकालयों को आयात करें -
import pandas as pd
मल्टीइंडेक्स पांडा वस्तुओं के लिए एक बहु-स्तरीय, या पदानुक्रमित, अनुक्रमणिका वस्तु है। सरणियाँ बनाएँ -
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
"नाम" पैरामीटर प्रत्येक सूचकांक स्तर के लिए नाम निर्धारित करता है। From_arrays() का उपयोग मल्टीइंडेक्स बनाने के लिए किया जाता है -
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) मल्टीइंडेक्स कन्वर्ट करें -
print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",multiIndex.to_flat_index()) उदाहरण
निम्नलिखित कोड है -
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# display the MultiIndex
print("The Multi-index...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# Convert the MultiIndex
print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",multiIndex.to_flat_index()) आउटपुट
यह निम्नलिखित आउटपुट देगा -
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris')],
names=['ranks', 'student'])
The levels in Multi-index...
[[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]
Converting a MultiIndex to an Index of Tuples containing the level values...
Index([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], dtype='object')