Pandas
Indexing and Selecting
Select rows and columns with loc, iloc, and masks.
By EZ4Code Team
indexinglociloc
Code
import pandas as pd
df = pd.DataFrame({"name": ["A", "B", "C"], "age": [30, 25, 35]}, index=["x", "y", "z"])
# Label-based
row = df.loc["y"]
sub = df.loc[["x", "z"], ["name"]]
mask = df.loc[df["age"] > 28]
# Position-based
first = df.iloc[0]
block = df.iloc[:2, 1]
last_row = df.iloc[-1]
# Set and reset index
df2 = df.reset_index(drop=True)
df_idx = df.set_index("name")
# At for scalar
val = df.at["x", "age"]Explanation
loc selects by label and supports boolean masks, while iloc selects by integer position like NumPy slicing. at and iat are fast scalar accessors. set_index and reset_index move a column into or out of the index without copying the data.
More Pandas Snippets
DataFrame Creation
Build DataFrames from dicts, lists, and files.
GroupBy Operations
Split, aggregate, and transform with groupby.
Merge and Join
Combine frames with merge and concat.
Pivot Tables
Reshape data with pivot, melt, and pivot_table.
Time Series
Resample, shift, and roll windows over time data.
Missing Data
Detect, fill, and drop NaN values.