Python | Pandas MultiIndex.from_product()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.from_product()
function make a MultiIndex from the cartesian product of multiple iterables.
Syntax: MultiIndex.from_product(iterables, sortorder=None, names=None)
Parameters :
iterables : Each iterable has unique labels for each level of the index.
sortorder : Level of sortedness (must be lexicographically sorted by that level).
names : Names for the levels in the index.
Returns: index : MultiIndex
Example #1: Use MultiIndex.from_product()
function to construct a MultiIndex from the cartesian product of multiple iterables.
import pandas as pd
Price = [ 20 , 35 , 60 , 85 ]
Name = [ 'Vanilla' , 'Strawberry' ]
print (Price)
print ( "\n" , Name)
|
Output :
Now let’s create the MultiIndex using the above two iterables.
midx = pd.MultiIndex.from_product([Name, Price],
names = [ 'Name' , 'Price' ])
print (midx)
|
Output :
As we can see in the output, the function has created a MultiIndex object using the cartesian product of these two iterables.
Example #2: Use MultiIndex.from_product()
function to construct a MultiIndex from the cartesian product of multiple iterables.
import pandas as pd
Snake = [ 'Viper' , 'Cobra' ]
Variety = [ 'Brown' , 'Yellow' , 'Black' ]
print (Snake)
print ( "\n" , Variety)
|
Output :
Now let’s create the MultiIndex using the above two iterables.
midx = pd.MultiIndex.from_product([Snake, Variety],
names = [ 'Snake' , 'Variety' ])
print (midx)
|
Output :
The function has created a MultiIndex using the two iterables.
Last Updated :
24 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...