How to read CSV file in Python using Pandas Library?
CSV files are generally used to store information. We can use this CSV file programmatically to for data analysis and data processing. To do this, we need to read data from CSV programmatically. CSV format is one of the most popular format types to exchange data.
Keeping it in mind, I think to show you how to read CSV file in Python programming language. So let’s continue reading and learning this post:
To read CSV file in Python we are going to use the Pandas library. Pandas is a popular library that is widely used in data analysis and data science.
If you don’t have Pandas installed on your computer, first install it. The installation instruction is available on Pandas website.
After you install the pandas, you need a CSV file. If you want to follow this tutorial exactly, then download the CSV that I am using in this tutorial and keep it inside a directory. In my case, I have created a directory “csv” and where my CSV file is located.
The CSV file contains records of crime which contains crime date and time, address, district and some more type of data like this. You can check it by opening the CSV file.
Now let’s start writing our Python code.
At first, let’s import the pandas:
import pandas as pd
Here we have just take pandas as pd so that we only have to write pd instead of pandas to save time and work during writing code.
Now below is the code to get all the data from the CSV file into a variable which we have named “data”
data = pd.read_csv("csv/crime.csv")
We can see if our CSV loaded inside our variable or not by printing it on the console:
We will able to see our CSV.
Now we will print CSV content by headers. Here headers are “cdatetime”, “address”, “district” and all these types of column names.
For example, if we want to print address from the CSV file, then below is how we can do it:
We can also get the data by index number for a particular header just like you can see below:
Now we will see the address with index number 16.
So we have seen how we can ready CSV file in Python very easily using Pandas library.