How to Create A Dataframe From CSV File in Python
To create a dataframe from a CSV file in Python, you can use the read_csv() function from the pandas library.
The following example shows how to create a dataframe from a CSV file using the read_csv() function.
Using read_csv() Function
We can use the read_csv() function to read a CSV file into a dataframe.
Suppose we have the following CSV file named data.csv
:
Date,Product_Code,Product_Name,Price,Status
01-03-2023,A-101,Laptop,4500,1
01-03-2023,A-102,Mobile,550,1
01-03-2023,A-103,Printer,250,1
01-03-2023,B-101,Keyboard,50,0
02-03-2023,B-102,Scanner,350,1
02-03-2023,B-104,Mouse,50,1
We can read this CSV file into a dataframe using the read_csv() function:
# Import pandas library
import pandas as pd
# Read the CSV file into a Pandas dataframe
df = pd.read_csv('data.csv')
# Display the dataframe
print(df)
Output: 👇️
Date Product_Code Product_Name Price Status
0 01-03-2023 A-101 Laptop 4500 1
1 01-03-2023 A-102 Mobile 550 1
2 01-03-2023 A-103 Printer 250 1
3 01-03-2023 B-101 Keyboard 50 0
4 02-03-2023 B-102 Scanner 350 1
5 02-03-2023 B-104 Mouse 50 1
In this example, we use the read_csv() function to read the CSV file data.csv
into a dataframe df.
The output shows the dataframe created from the CSV file.
Conclusion
We can use the read_csv() function from the pandas library to create a dataframe from a CSV file in Python.