Are you figuring out how to read in a csv file in Pandas? Then, this tutorial will cover it using the read_csv() function of Pandas.
Step 1: Prepare your csv data for Pandas
In most cases, people often fail to create a proper csv data format and thus, they aren’t able to read csv files in Pandas.
Here are some key points you have to take in mind for preparing your csv file for Pandas:
- Make sure the data structure is actually csv.
Consider you want to import data into a dataframe as shown below:
Then, the data should be structured in the following way in the csv file.
"Name","Age" "Pamela","32" "John","48" "Mary","21"
2. Make sure the data file is in .csv format and not .txt format.
Once you have your data ready, make sure to save it in a .csv format.
Step 2: Use read_json() function in Pandas
Once you have your csv file ready, you can easily read it in as a dataframe in Pandas using the read_csv() function in Pandas.
# Import the Pandas Library as pd import pandas as pd # Import using the read_csv() function pd.read_csv('Path where you saved the CSV file\File Name.csv')
Since we had named our csv file as ‘data.csv’ in step 1, we will be reading it in using the read_csv function in pandas in the following way:
# Import the Pandas Library as pd import pandas as pd # Import using the read_csv() function df = pd.read_csv ('data.csv') print (df)
As you can see, it is working! Now, you can perform all sorts of other operations on the csv data as a Pandas dataframe.
Note: If you have the data.csv file in a different folder than where you have your Jupyter Notebook, then, use a full file name such as ‘C:\Users\MSI\Desktop\data.csv’.
We hope that you now know how to read in a csv file using Pandas.
To learn everything about Pandas, make sure to visit the Pandas Full Course.