Project selected columns
Retain a known subset of columns by passing their exact names.
Pandas · Module
DataFrame.filter selects rows or columns by their labels using exact names, substring matching, or regular expressions. It does not inspect the values in the DataFrame.
DataFrame.filter returns a same-type object containing labels selected by an explicit collection, substring match, or regular expression. For DataFrames, the default axis is columns; set axis to index or 0 to select rows, and remember that matching examines labels rather than cell values.
DataFrame.filter(*items=None*, *like=None*, *regex=None*, *axis=None*)| Name | Type | Description |
|---|---|---|
items | list-like, optional | Labels to retain when they occur in the selected axis. |
like | str, optional | Substring that must occur in a selected-axis label. |
regex | str, optional | Regular expression searched against each selected-axis label. |
axis | {0 or ‘index’, 1 or ‘columns’, None}, default None | Axis to inspect: 0 or index for rows, 1 or columns for columns, or None. |
A DataFrame containing the selected labels; the returned object has the same type as the input object.
import pandas as pd
df = pd.DataFrame(
[[1, 2, 3], [4, 5, 6]],
index=["mouse", "rabbit"],
columns=["one", "two", "three"],
)
columns = df.filter(items=["one", "three"])
rows = df.filter(like="bbi", axis="index")
regex_columns = df.filter(regex="e$", axis="columns")
print(columns)
print(rows)
print(regex_columns)Selects named columns, an index label containing a substring, and columns whose labels end in “e”.
Retain a known subset of columns by passing their exact names.
Find rows whose index labels contain a meaningful substring.
Select columns following a naming convention, such as a suffix or prefix.
DataFrame.filter selects a subset using labels. The available modes are exact labels through items, substring matching through like, or regular expressions through regex; the method returns the same general type as its input.
Follow-up: How would you select rows rather than columns? Pass axis="index" or axis=0, because a DataFrame defaults to filtering its columns.
The default axis is the DataFrame’s information axis, which is columns. Set axis="index" or axis=0 when matching row labels, or axis="columns" or axis=1 when matching column labels.
Follow-up: What happens if axis is omitted while using like? The substring is matched against column labels.
items keeps labels present in the supplied list-like object, like keeps labels containing a substring, and regex keeps labels for which a regular-expression search succeeds. These modes operate on labels, not data values.
Follow-up: How can columns ending in “e” be selected? Use regex="e$" with axis=1 or axis="columns".
Series.filterDataFrame.locDataFrame.select_dtypes