Use a list of values to select rows from a Pandas DataFrame

PandasServer Side ProgrammingProgramming

To select the rows from a Pandas DataFrame based on input values, we can use the isin() method.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Create a list of values for selection of rows.

  • Print the selected rows with the given values.

  • Next, print the rows that were not selected.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)

print "Input DataFrame:\n", df
values = [1, 2]
print "Selected Rows:\n", df[df['x'].isin(values)]
print "Uselected Rows:\n", df[~df['x'].isin(values)]

Output

Input DataFrame:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

Selected Rows:
   x  y  z
1  2  1  1
2  1  5  5

Unselected Rows:
   x  y  z
0  5  4  4
3  9 10  0
raja
Published on 30-Aug-2021 09:35:40
Advertisements