In our previous articles, we discussed how to drop rows and columns from a DataFrame using the pandas Python library. The pandas DataFrame.filter() function does the opposite of the drop() function. It selects rows and columns from the DataFrame using the indexes and keeps them. Let’s look at an example:
import pandas list1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] df1 = pandas.DataFrame(list1) print("df1: \n", df1) df2 = df1.filter([0, 1, 3], axis=0) print("df2: \n", df2) df3 = df1.filter([0, 1], axis=1) print("df3: \n", df3)
Here, df1 is a DataFrame that looks like the following:
df1: 0 1 2 3 4 0 1 2 3 4 5 1 6 7 8 9 10 2 11 12 13 14 15 3 16 17 18 19 20
We are using the following Python statement to filter only rows 0, 1, and 3 from the DataFrame.
df2 = df1.filter([0, 1, 3], axis=0)
Please note that axis=0 parameter indicates that we are filtering rows.
Next, we are using the following Python statement …






0 Comments