How to read specific columns from a CSV file in Python
In this tutorial, you will learn how to read specific columns from a CSV file in Python.
Comma Separated Values (CSV) Files
CSV (Comma Separated Values) files are files that are used to store tabular data such as a database or a spreadsheet. In a CSV file, tabular data is stored in plain text indicating each file as a data record.
Pandas Library
To read a CSV file we use the Pandas library available in python. Pandas library is used for data analysis and manipulation. It is a very powerful and easy to use library to create, manipulate and wrangle data.
import pandas as pd temp=pd.read_csv("filename.csv",usecols=['column1','column2']) print(temp)
Read specific columns from a CSV file in Python
Pandas consist of read_csv function which is used to read the required CSV file and usecols is used to get the required columns.
We have to make sure that python is searching for the file in the directory it is present. In order to that, we need to import a module called os. This module provides functions to interact with the Operating System.
import pandas as pd import os #chdir is used to change the directory. os.chdir('C://Users//Desktop//readcsv') temp=pd.read_csv("filename.csv",usecols=['column1','column2']) print(temp)
Using the os.chdir function we can change the current working directory to the directory in which our CSV file is present.
You may also read:
Leave a Reply