Python | Pandas MultiIndex.from_tuples()
Last Updated :
24 Dec, 2018
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_tuples()
function is used to convert list of tuples to MultiIndex. It is one of the several ways in which we construct a MultiIndex.
Syntax: MultiIndex.from_tuples(tuples, sortorder=None, names=None)
Parameters :
tuples : Each tuple is the index of one row/column.
sortorder : Level of sortedness (must be lexicographically sorted by that level)
Returns: index : MultiIndex
Example #1: Use MultiIndex.from_tuples()
function to construct a MultiIndex using python tuples.
import pandas as pd
tuples = [( 30 , 'Larry' ), ( 20 , 'Mike' ),
( 18 , 'David' ), ( 25 , 'Tim' )]
print (tuples)
|
Output :
Now let’s create the MultiIndex using the Tuples.
midx = pd.MultiIndex.from_tuples(tuples, names = ( 'Age' , 'Name' ))
print (midx)
|
Output :
As we can see in the output, the function has created a MultiIndex object using the Tuples.
Example #2: Use MultiIndex.from_tuples()
function to construct a MultiIndex using python tuples.
import pandas as pd
tuples = [( 'Physics' , 85 ), ( 'Chemistry' , 88 ),
( 'Maths' , 95 ), ( 'Computers' , 99 )]
print (tuples)
|
Output :
Now let’s create the MultiIndex using the Tuples.
midx = pd.MultiIndex.from_tuples(tuples, names = ( 'Subject' , 'Marks' ))
print (midx)
|
Output :
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...