Menu

Reading CSV and Excel Files with Pandas

Reading CSV and Excel Files with Pandas

Data science projects often begin with data stored in files such as CSV spreadsheets or Excel workbooks. Python's Pandas library provides convenient functions for loading these files into DataFrames, where the data can be inspected, cleaned, and analyzed.

Loading a CSV File

CSV (Comma-Separated Values) files store tabular data as text, with each line representing a record and separators distinguishing columns.

Suppose you have a file named sales.csv:

Product,Region,Sales,Units

Laptop,North,55000,10

Phone,South,30000,15

Tablet,West,25000,12

Monitor,North,18000,8

You can load it using pd.read_csv().

import pandas as pd

df = pd.read_csv("sales.csv")

print(df.head())

print(df.shape)

print(df.columns)

Pandas automatically identifies the column names from the first row and attempts to infer appropriate data types.

If the file is stored in a different folder, provide the correct file path.

df = pd.read_csv("data/sales.csv")

On Windows, you can use a raw string for a file path:

df = pd.read_csv(r"C:\Data\sales.csv")

Loading Excel Files

Pandas can also read Excel workbooks using read_excel().

df = pd.read_excel("sales.xlsx", sheet_name="January")

print(df.head())

The sheet_name parameter specifies which worksheet to load. You may need to install an Excel-reading dependency, such as openpyxl, depending on the file format.

pip install pandas openpyxl

Reading Only Required Columns

Large files may contain columns that are not needed for a particular analysis. You can load only the relevant columns.

df = pd.read_csv(

"sales.csv",

usecols=["Product", "Sales"]

)

print(df)

Loading fewer columns can reduce memory usage and simplify subsequent processing.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details