w3resource

Python Scikit learn: Drop Id column from a given Dataframe and print the modified part

Python Machine learning Iris Basic: Exercise-7 with Solution

Write a Python program to drop Id column from a given Dataframe and print the modified part. Call iris.csv to create the Dataframe.

Sample Solution:

Python Code:

import pandas as pd
data = pd.read_csv("iris.csv")
print("Original Data:")
print(data.head())
new_data = data.drop('Id',axis=1)
print("After removing id column:")
print(new_data.head()) 

Output:

Original Data:
   Id  SepalLengthCm     ...       PetalWidthCm      Species
0   1            5.1     ...                0.2  Iris-setosa
1   2            4.9     ...                0.2  Iris-setosa
2   3            4.7     ...                0.2  Iris-setosa
3   4            4.6     ...                0.2  Iris-setosa
4   5            5.0     ...                0.2  Iris-setosa

[5 rows x 6 columns]
After removing id column:
   SepalLengthCm  SepalWidthCm     ...       PetalWidthCm      Species
0            5.1           3.5     ...                0.2  Iris-setosa
1            4.9           3.0     ...                0.2  Iris-setosa
2            4.7           3.2     ...                0.2  Iris-setosa
3            4.6           3.1     ...                0.2  Iris-setosa
4            5.0           3.6     ...                0.2  Iris-setosa

[5 rows x 5 columns]

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get observations of each species (setosa, versicolor, virginica) from iris data.
Next:Write a Python program to access first four cells from a given Dataframe using the index and column labels. Call iris.csv to create the Dataframe.

What is the difficulty level of this exercise?