to filter columns 0 and 1 from the DataFrame.
df3 = df1.filter([0, 1], axis=1)
Here, axis=1 parameter indicates that we are filtering columns.
So, the output of the above program will be:
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
df2:
0 1 2 3 4
0 1 2 3 4 5
1 6 7 8 9 10
3 16 17 18 19 20
df3:
0 1
0 1 2
1 6 7
2 11 12
3 16 17
Please note that if the rows and columns of the DataFrame are labeled, then we can use regular expressions to filter those rows and columns. Let’s look at an example:
import pandas
df4 = pandas.read_csv("iris.csv")
print(df4.head())
df5 = df4.filter(like="length", axis=1)
print("df5: \n", df5.head())
df6 = df4.filter(regex="^petal", axis=1)
print("df6: \n", df6.head())
Here, we are first reading the iris dataset from a CSV file. After that, we are using the following Python statement to filter all columns that contain the string “length”.
df5 = df4.filter(like="length", axis=1)
Next, we are using the following Python statement to filter the columns that match the regular expression “^petal”. In other words, we are filtering all columns whose labels start with the string “petal”.
df6 = df4.filter(regex="^petal", axis=1)
The output of the above program will be:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
df5:
sepal_length petal_length
0 5.1 1.4
1 4.9 1.4
2 4.7 1.3
3 4.6 1.5
4 5.0 1.4
df6:
petal_length petal_width
0 1.4 0.2
1 1.4 0.2
2 1.3 0.2
3 1.5 0.2
4 1.4 0.2








































0 Comments