w3resource

Pandas: Extract data from MultiIndex levels DataFrame

Pandas Indexing: Exercise-14 with Solution

Write a Pandas program to extract a single row, rows and a specific value from a MultiIndex levels DataFrame.

Sample Solution:

Python Code :

import pandas as pd 
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'],
          ['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print(sales_tuples)
print("\nConstruct a Dataframe using the said MultiIndex levels: ")
df = pd.DataFrame(np.random.randn(8, 5), index=sales_index)
print(df)

print("\nExtract a single row from the said dataframe:")
print(df.loc[('sale2', 'city2')])
print("\nExtract a single row from the said dataframe:")
print(df.loc[('sale2', 'city2')])

print("\nExtract number of rows from the said dataframe:")
print(df.loc['sale1'])
print("\nExtract number of rows from the said dataframe:")
print(df.loc['sale3'])

print("\nExtract a single value from the said dataframe:")
print(df.loc[('sale1', 'city2'), 1])
print("\nExtract a single value from the said dataframe:")
print(df.loc[('sale4', 'city1'), 4])

Sample Output:

[('sale1', 'city1'), ('sale1', 'city2'), ('sale2', 'city1'), ('sale2', 'city2'), ('sale3', 'city1'), ('sale3', 'city2'), ('sale4', 'city1'), ('sale4', 'city2')]

Construct a Dataframe using the said MultiIndex levels: 
                    0         1         2         3         4
sale  city                                                   
sale1 city1  1.138551  0.507722 -0.870609 -0.186479 -1.038967
      city2 -0.002357  0.227624 -0.146152 -0.185473 -0.741184
sale2 city1 -1.307382  0.846347 -1.011645 -1.354593  2.208438
      city2  0.895843  0.350624  0.674705 -0.920561  0.610004
sale3 city1  0.571192  0.417562 -1.580535 -0.170085  1.258469
      city2  0.455347 -0.285652 -0.632070 -1.259128  0.710763
sale4 city1  0.178355  1.561962  1.627784 -0.097158  1.340233
      city2 -1.211935  0.256773  0.584134  1.505608 -1.559970

Extract a single row from the said dataframe:
0    0.895843
1    0.350624
2    0.674705
3   -0.920561
4    0.610004
Name: (sale2, city2), dtype: float64

Extract a single row from the said dataframe:
0    0.895843
1    0.350624
2    0.674705
3   -0.920561
4    0.610004
Name: (sale2, city2), dtype: float64

Extract number of rows from the said dataframe:
              0         1         2         3         4
city                                                   
city1  1.138551  0.507722 -0.870609 -0.186479 -1.038967
city2 -0.002357  0.227624 -0.146152 -0.185473 -0.741184

Extract number of rows from the said dataframe:
              0         1         2         3         4
city                                                   
city1  0.571192  0.417562 -1.580535 -0.170085  1.258469
city2  0.455347 -0.285652 -0.632070 -1.259128  0.710763

Extract a single value from the said dataframe:
0.22762367059081048

Extract a single value from the said dataframe:
1.340233465712309

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to construct a DataFrame using the MultiIndex levels as the column and index.

Next: Write a Pandas program to rename names of columns and specific labels of the Main Index of the MultiIndex dataframe.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Inspect an object in Python

Example:

test_obj = [1, 3, 5, 7]
print( dir(test_obj) )

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']