Introduction: What is CSV?
CSV (Comma Separated Values) is one of the most common file formats used to store tabular data. The data is structured in rows and columns, and each row represents a record or data point. CSV files are easy to create and compatible with a variety of software platforms, making them ideal for data exchange and analysis.Python has a built-in library for parsing and manipulating CSV files. In this article, we’ll discuss how to load a CSV file in Python using different techniques.Method 1: Reading CSV with csv module
Python’s csv module is an efficient way to read and write CSV files. It provides a variety of functions to read, write and manipulate CSV files. The csv module can handle different formats of CSV files, including those with custom delimiters and quotes.To use the csv module, you first need to import it in your Python script:import csv
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
Method 2: Using Pandas library
Pandas is a popular data analysis library in Python. It provides a powerful set of functions to manipulate and analyze data, including reading and writing CSV files.To use Pandas, you need to first install it using pip:pip install pandas
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Method 3: Using NumPy library
NumPy is another popular library for numerical computing in Python. It provides a set of functions to manipulate arrays and matrices of numerical data. NumPy also has a function to load CSV files into arrays.To use NumPy, you need to first install it using pip:pip install numpy
import numpy as np
data = np.loadtxt('data.csv', delimiter=',')
print(data)