Python - Drop specific rows from multiindex Pandas Dataframe

PythonServer Side ProgrammingProgramming

To drop specific rows rom multiindex dataframe, use the drop() method. At first, let us create a multi-index array −

arr = [np.array(['car', 'car', 'car','bike', 'bike', 'bike', 'truck', 'truck', 'truck']),
   np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])]

Next, create multiindex dataframe and set index also −

dataFrame = pd.DataFrame(
   np.random.randn(9, 3), index=arr, columns=['Col 1', 'Col 2', 'Col 3'])

dataFrame.index.names = ['level 0', 'level 1']

Now, drop specific row −

dataFrame.drop(('car','valueA'), axis=0, inplace=True)

Example

Following is the code −

import numpy as np
import pandas as pd

# multiindex array
arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']),
   np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])]

# forming multiindex dataframe
dataFrame = pd.DataFrame(
   np.random.randn(9, 3), index=arr,columns=['Col 1', 'Col 2', 'Col 3'])

dataFrame.index.names = ['level 0', 'level 1']
print(dataFrame)

print("\nDropping specific row...\n");
dataFrame.drop(('car','valueA'), axis=0, inplace=True)
print(dataFrame)

Output

This will produce the following output −

                    Col 1       Col 2      Col 3
level 0 level 1
car     valueA     0.845965   -0.850953   -0.335662
        valueB     0.534764   -0.107635    1.008855
        valueC    -0.507910   -0.664625    1.671653
bike    valueA    -0.475751   -0.244113    0.672352
        valueB    -0.273670    1.118635    0.428750
        valueC    -1.064504   -0.344729    0.481037
truck   valueA    -0.508659    1.352390    1.382799
        valueB     1.144299   -0.092568   -1.071624
        valueC    -0.710767    0.967018   -0.047430

Dropping specific row...

                     Col 1      Col 2     Col 3
level 0 level 1
car     valueB      0.534764  -0.107635   1.008855
        valueC     -0.507910  -0.664625   1.671653
bike    valueA     -0.475751  -0.244113   0.672352
        valueB     -0.273670   1.118635   0.428750
        valueC     -1.064504  -0.344729   0.481037
truck   valueA     -0.508659   1.352390   1.382799
        valueB      1.144299  -0.092568  -1.071624
        valueC     -0.710767   0.967018  -0.047430
raja
Published on 09-Sep-2021 12:11:02
Advertisements