pandas and NumPy 3 cheatsheet

pandas and NumPy 3: Selecting and filtering

8 common pandas and NumPy 3 tasks.

Select columns

Pick one column as a Series, or several as a DataFrame.

df["name"]
df[["name", "age"]]

Filter rows

Keep rows that meet conditions. Combine them with & and |, each in parentheses.

df[(df["age"] > 30) & (df["country"] == "UK")]

Filter with a string expression

Write conditions as readable text.

df.query("age > 30 and country == 'UK'")

Select by label

Select rows and columns by label with loc.

df.loc[df["age"] > 30, ["name", "age"]]

Select by position

Select the first five rows and first two columns by position.

df.iloc[:5, :2]

Match a list of values

Keep rows whose value is in a list.

df[df["country"].isin(["UK", "US"])]

Sort rows

Sort by one or more columns.

df.sort_values(["country", "age"], ascending=[True, False])

Get the top rows

Return the five rows with the largest values.

df.nlargest(5, "revenue")

Was this page helpful?