How to drop ROW and COLUMN in a Pandas DataFrame?

This recipe helps you drop ROW and COLUMN in a Pandas DataFrame

Recipe Objective

Have you ever tried to remove a column or row on the basis of condition ? So this is a code snippet is for you.

So this is the recipe on how we can drop ROW and COLUMN in a Pandas DataFrame

Master the Art of Data Cleaning in Machine Learning

Step 1 - Import the library

import pandas as pd

We have imported only pandas which will be needed for the dataset.

Step 2 - Setting up the Data

We have created a dictionary of data and passed it in pd.DataFrame to make a dataframe with columns 'last_name', 'age', 'Comedy_Score' and 'Rating_Score'. raw_data = { 'last_name': ['Copper', 'Koothrappali', 'Hofstadter', 'Wolowitz', 'Fowler'], 'age': [42, 38, 36, 41, 35], 'Comedy_Score': [9, 7, 8, 8, 5], 'Rating_Score': [25, 25, 49, 62, 70] } df = pd.DataFrame(raw_data, columns = [ 'first_name', 'last_name', 'age', 'Comedy_Score', 'Rating_Score'], index = ['Sheldon', 'Raj', 'Leonard', 'Howard', 'Amy']) print(df)

Step 3 - Droping Rows and Columns

Here we will be removing rows and columns on some conditions.

    • Droping an observation (row)

print(df.drop(['Sheldon', 'Amy']))

    • Droping a variable (column)

print(df.drop('age', axis=1))

    • Droping a row if it contains a certain value (in this case, 'Cooper')

print(df[df.last_name != 'Copper'])

    • Droping a row by row number (in this case, row 3)

print(df.drop(df.index[2]))

    • Keeping top 3 rows only

print(df[:3])

    • Droping last 3 rows

print(df[:-3])

So the output comes as:

            last_name  age  Comedy_Score  Rating_Score
Sheldon        Copper   42             9            25
Raj      Koothrappali   38             7            25
Leonard    Hofstadter   36             8            49
Howard       Wolowitz   41             8            62
Amy            Fowler   35             5            70

            last_name  age  Comedy_Score  Rating_Score
Raj      Koothrappali   38             7            25
Leonard    Hofstadter   36             8            49
Howard       Wolowitz   41             8            62

            last_name  Comedy_Score  Rating_Score
Sheldon        Copper             9            25
Raj      Koothrappali             7            25
Leonard    Hofstadter             8            49
Howard       Wolowitz             8            62
Amy            Fowler             5            70

            last_name  age  Comedy_Score  Rating_Score
Raj      Koothrappali   38             7            25
Leonard    Hofstadter   36             8            49
Howard       Wolowitz   41             8            62
Amy            Fowler   35             5            70

            last_name  age  Comedy_Score  Rating_Score
Sheldon        Copper   42             9            25
Raj      Koothrappali   38             7            25
Howard       Wolowitz   41             8            62
Amy            Fowler   35             5            70

            last_name  age  Comedy_Score  Rating_Score
Sheldon        Copper   42             9            25
Raj      Koothrappali   38             7            25
Leonard    Hofstadter   36             8            49

            last_name  age  Comedy_Score  Rating_Score
Sheldon        Copper   42             9            25
Raj      Koothrappali   38             7            25
?

Download Materials

What Users are saying..

profile image

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

Detectron2 Object Detection and Segmentation Example Python
Object Detection using Detectron2 - Build a Dectectron2 model to detect the zones and inhibitions in antibiogram images.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

Deploying Machine Learning Models with Flask for Beginners
In this MLOps on GCP project you will learn to deploy a sales forecasting ML Model using Flask.

CycleGAN Implementation for Image-To-Image Translation
In this GAN Deep Learning Project, you will learn how to build an image to image translation model in PyTorch with Cycle GAN.

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.

Time Series Analysis with Facebook Prophet Python and Cesium
Time Series Analysis Project - Use the Facebook Prophet and Cesium Open Source Library for Time Series Forecasting in Python