how to turn a csv file into a dataframe in python

To turn a CSV (Comma-Separated Values) file into a DataFrame in Python, we can use the read_csv() function provided by the pandas library.

First, we need to import pandas library and then use the read_csv() function with the file path of the CSV file as the argument.

main.py
import pandas as pd

df = pd.read_csv('path/to/csv/file.csv')
62 chars
4 lines

This will create a DataFrame df that contains the data from the CSV file. By default, the first row of CSV file is assumed to be header and used as column names. If the CSV file doesn't have a header row, we can set the header parameter to None.

main.py
df = pd.read_csv('path/to/csv/file.csv', header=None)
54 chars
2 lines

If the CSV file uses a separator other than a comma, we can use the sep parameter to specify the separator.

main.py
df = pd.read_csv('path/to/csv/file.csv', sep=';')
50 chars
2 lines

Once the DataFrame is created, we can use various functions provided by pandas library to perform data manipulation and analysis on the data.

gistlibby LogSnag