. Advertisement .
..3..
. Advertisement .
..4..
Python is a popular programming language because of its versatility. In it, the CSV Module provides Python programmers with the ability to parse CSV (Comma Separated Values) files. In this article, we will introduce to you “Method to Import CSV file into python using Pandas”. Follow along to get the information you want!
How is the CSV file structured?
A CSV file consists of 3 parts:
- Part 1: in the spreadsheet, it corresponds to the first column, used to represent the names of the columns, each column will be separated by commas.
- Part 2: corresponds to the last column
- Part 3: includes rows with equivalent structure, each column will have corresponding content.
Note, in a spreadsheet, each line of text has a different value.
How to import CSV file into Python using Pandas
As you know in previous posts, Pandas is an open source library that allows you to process data in Python. Pandas provides an easy way to create, manipulate, and delete data. Next we will give step by step instructions for you to import CSV files to Python using Pandas.
Here are the steps:
- Copy the file path
- Syntax declaration
- Run the code and get the results.
To import a CSV file into Python we will use the read_csv()
function.
Here is the syntax to use:
import pandas as pd
df = pd.read_csv (r'Path where the CSV file is stored\File name.csv')
print (df)
Note: when declaring the CSV file import syntax, you should always make sure that the file extension is “.csv” and that the declared file name matches the actual file.
Below we will give a specific example for you to easily manipulate.
Here is your data file:
Site | Ranking | Views |
ITTutorial | 1 | 1.982.588 |
Geeksforgeek | 2 | 1.664.256 |
4 | 1.185.788 | |
Careerkarma | 3 | 1.376.255 |
You are saving the file in your computer, and the file path is as follows:
C:\Users\Kim\Desktop\SiteRanking.csv
After you have enough information, you will proceed to declare according to the syntax above and run the code. With the above path, we declare the following:
import pandas as pd
#read the csv file (put 'r' before the path string to address any special characters in the path, such as '').
#Don't forget to put the file name at the end of the path + ".csv"
df = pd.read_csv (r'C:\Users\Kim\Desktop\SiteRanking.csv')
print (df)
output:
Site Ranking Views
0 ITTutorial 1 1.982.588
1 Geeksforgeek 2 1.664.256
2 Reddit 4 1.185.788
3 Careerkarma 3 1.376.255
With that, you’ve done the steps to be able to import CSV files into python.
Conclusion
This is how you are able to solve this type of task “Method to import CSV file into Python using Pandas”. However, we have provided relevant expertise to develop a more research-oriented mindset, and make it easier for you to answer these type questions. Please leave a message below if you have any questions or comments. Thanks for reading!
Leave a comment