# Selecting Rows and Columns — NumPy / Pandas / scikit-learn

Source: https://www.skillbyai.com/en/numpy-pandas-sklearn/p-select

> loc, iloc, masks and query.

## Labels versus positions

`df["col"]` selects a column; `df.loc[rows, cols]` selects by **label** (including boolean masks); `df.iloc[rows, cols]` selects by **position**. Combine conditions with `&` and `|` and parentheses, not `and`/`or`. `query()` expresses filters as readable strings, and `sort_values` plus `head` gives top-N lists.

## Six ways to select, run

I ran this with Python 3.12.3 and pandas 3.0.6. Columns, label-based selection with a mask, positional slicing, a combined condition, a query string and a top-2 by price.

```python
import pandas as pd

df = pd.DataFrame({
    "city": ["Delhi", "Mumbai", "Pune", "Delhi", "Pune"],
    "product": ["pen", "mug", "pen", "lamp", "mug"],
    "units": [10, 4, 7, 1, 3],
    "price": [20.0, 250.0, 20.0, 1499.0, 250.0],
})
print(df["units"].tolist())
print(df.loc[df["city"] == "Pune", ["product", "units"]])
print(df.iloc[0:2, 0:2])
print(df[(df["units"] > 3) & (df["price"] < 100)])
print(df.query("city in ['Delhi', 'Mumbai'] and units >= 4"))
print(df.sort_values("price", ascending=False).head(2)[["product", "price"]])
```

Output:

```
[10, 4, 7, 1, 3]
  product  units
2     pen      7
4     mug      3
     city product
0   Delhi     pen
1  Mumbai     mug
    city product  units  price
0  Delhi     pen     10   20.0
2   Pune     pen      7   20.0
     city product  units  price
0   Delhi     pen     10   20.0
1  Mumbai     mug      4  250.0
  product   price
3    lamp  1499.0
4     mug   250.0
```

## Prefer loc for assignment

Use df.loc[mask, "col"] = value to update data; it is explicit and works correctly with copy-on-write.

**Quiz:** Which selects rows by integer position?

- [ ] query
- [ ] loc
- [x] iloc
- [ ] at with labels

*Answer:* iloc. i for integer position.
