Select rows from a Pandas DataFrame based on column values

PandasServer Side ProgrammingProgramming

To select rows from a DataFrame based on column values, we can take the following Steps −

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

  • Print the input DataFrame.

  • Use df.loc[df["x"]==2] to print the DataFrame when x==2.

  • Similarly, print the DataFrame when (x >= 2) and (x < 2).

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 "Given DataFrame is:\n", df

print "When column x value == 2:\n", df.loc[df["x"] == 2]

print "When column x value >= 2:\n", df.loc[df["x"] >= 2]

print "When column x value < 2:\n", df.loc[df["x"] < 2]

Output

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

When column x value == 2:
  x  y  z
1 2  1  1

When column x value >= 2:
   x  y  z
0  5  4  4
1  2  1  1
3  9 10  0

When column x value < 2:
  x  y  z
2 1  5  5
raja
Published on 30-Aug-2021 09:11:26
Advertisements