Menu

Selecting and Filtering Data

Selecting and Filtering Data

Data analysis often requires extracting specific columns or identifying rows that meet certain conditions. Pandas provides several methods for selecting the required information.

Selecting Columns

Use a column name in square brackets to select one column.

salary = df["Salary"]

print(salary)

To select multiple columns, pass a list of column names.

employee_data = df[["Employee", "Salary"]]

print(employee_data)

Selecting only relevant columns can make subsequent calculations clearer and reduce unnecessary processing.

Filtering Rows with Conditions

Suppose you want to identify employees earning more than ₹60,000.

high_salary = df[df["Salary"] > 60000]

print(high_salary)

You can combine conditions to apply more specific rules.

it_high_salary = df[

(df["Department"] == "IT") &

(df["Salary"] > 60000)

]

print(it_high_salary)

Use parentheses around individual comparisons when combining conditions with & or |.

Using loc and iloc

Pandas offers two important accessors:

  • loc selects rows and columns using labels.
  • iloc selects rows and columns using integer positions.

print(df.loc[0, "Employee"])

print(df.loc[0:2, ["Employee", "Salary"]])

print(df.iloc[0, 1])

print(df.iloc[0:2, 0:2])

With loc, a label-based slice includes the ending label when it exists. With iloc, the ending position is excluded, following Python's usual slicing convention.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details