Labs ICT
Pro Login

Selecting Rows

Slicing and filtering your data.

Selecting Rows

Let me give you the tools to grab specific rows from your data. There are several ways to do this, and each one has its sweet spot.

Slicing with iloc

If you know the position of the rows you want, slicing is your friend:


import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
        'Age': [25, 30, 35, 28, 32]}
df = pd.DataFrame(data)

print(df.iloc[0:3])
    

This grabs rows 0, 1, and 2 (remember, Python slicing excludes the end index). Think of it like selecting rows in Excel by their position.

Boolean Indexing

Here is where it gets powerful. Want rows where age is greater than 30?


print(df[df['Age'] > 30])
    

This is called boolean indexing. You create a condition, and Pandas filters the rows for you. It's like having a super-powered filter in Excel.

Combining Conditions

Need multiple conditions? Use `&` for AND and `|` for OR:


print(df[(df['Age'] > 25) & (df['Age'] < 35)])
    

One thing that confused me at first was the parentheses. You need them around each condition. Without them, Python gets confused about the order of operations.

Try it Yourself →

Key Takeaways

  • `iloc` selects rows by position (integer location)
  • Boolean indexing filters rows based on conditions
  • Use `&` for AND and `|` for OR in conditions
  • Always wrap individual conditions in parentheses