Pandas DataFrame | filter method
Start your free 7-days trial now!
Pandas DataFrame.filter(~)
method returns the rows or columns where the label matches the specified pattern.
The method applies filtering based on the labels of the columns/rows, and not on the actual data.
Parameters
1. items
| list-like
| optional
Extract rows or columns where the label is included in items
.
2. like
| string
| optional
Extract rows or columns where the label contains like
.
3. regex
| string
(regular expression) | optional
Extract rows or columns where the label matches regex
.
4. axis
| int
or string
| optional
Whether to extract rows or columns:
Axis | Description |
---|---|
| Extract rows. |
| Extract columns. |
By default, axis=1
.
You can only specify one out of items
, like
and regex
.
Return value
A new DataFrame
containing the rows or columns where the label matches the specified pattern.
Examples
Consider the following DataFrame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[7,8,9]}, index=["a","b","c"])df
A B Ca 1 4 7b 2 5 8c 3 6 9
Specifying items
To get columns A
and C
:
df.filter(items=["A","C"])
A Ca 1 7b 2 8c 3 9
Getting rows
To get rows a
and c
:
df.filter(items=["a","c"], axis=0)
A B Ca 1 4 7c 3 6 9
Specifying like and regex
Consider the following DataFrame:
df = pd.DataFrame({"ABC":[1,2,3],"BCD":[4,5,6],"E":[7,8,9]}, index=["a","b","c"])df
ABC BCD Ea 1 4 7b 2 5 8c 3 6 9
To get columns where the label contains the substring "BC"
:
df.filter(like="BC")
ABC BCDa 1 4b 2 5c 3 6
To get columns where the label contains the character "B"
:
df.filter(regex=".*B.*")
ABC BCDa 1 4b 2 5c 3 6