close

How to drop a specific column of csv file while reading it using pandas?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to drop a specific column of csv file while reading it using pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to drop a specific column of csv file while reading it using pandas?

  1. How to drop a specific column of csv file while reading it using pandas?

    If you don't know the column names but you want first N columns from dataframe. You can do it by

  2. drop a specific column of csv file while reading it using pandas

    If you don't know the column names but you want first N columns from dataframe. You can do it by

Method 1

If you know the column names prior, you can do it by setting usecols parameter

When you know which columns to use

Suppose you have csv file with columns ['id','name','last_name'] and you want just ['name','last_name']. You can do it as below:

import pandas as pd
df = pd.read_csv("sample.csv", usecols = ['name','last_name'])

when you want first N columns

If you don’t know the column names but you want first N columns from dataframe. You can do it by

import pandas as pd
df = pd.read_csv("sample.csv", usecols = [i for i in range(n)])

Edit

When you know name of the column to be dropped

# Read column names from file
cols = list(pd.read_csv("sample_data.csv", nrows =1))
print(cols)

# Use list comprehension to remove the unwanted column in **usecol**
df= pd.read_csv("sample_data.csv", usecols =[i for i in cols if i != 'name'])

Method 2

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read