Python Pandas read_csv() Method



The read_csv() method in Python's Pandas library allows you to read or load data from a CSV (Comma-Separated Values) file into a Pandas DataFrame. This method supports reading CSV files from various storage back-ends, including local files, URLs, and cloud storage services. It also supports optional iterating or breaking of the CSV data into chunks.

CSV is a plain-text format for storing tabular data where each line represents a row, and columns are separated by a comma ",". It is a common delimiter for CSV files, and file has .csv extension.

CSV is a widely used format for data exchange and storage, and his method is one of the most commonly used methods in Pandas for reading structured data. It efficiently loads large datasets, supports various formats, and offers customization through numerous parameters.

Syntax

The syntax of the read_csv() method is as follows −

pandas.read_csv(filepath_or_buffer, *, sep=<no_default>, delimiter=None, header='infer', names=<no_default>, index_col=None, usecols=None, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=<no_default>, skip_blank_lines=True, parse_dates=None, infer_datetime_format=<no_default>, keep_date_col=<no_default>, date_parser=<no_default>, date_format=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal='.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors='strict', dialect=None, on_bad_lines='error', delim_whitespace=<no_default>, low_memory=True, memory_map=False, float_precision=None, storage_options=None, dtype_backend=<no_default>)

Parameters

The Python Pandas read_csv() method accepts the below parameters −

  • filepath_or_buffer: The file path, URL, or file-like object to read CSV file from. Supports various schemes like http, ftp, s3, etc.

  • sep: Specifies the delimiter(Character or regex pattern) to use. Defaults to a comma ",".

  • delimiter: An alternative to sep parameter.

  • header: Specifies the row number to use as column names. Defaults to infer, meaning Pandas will attempt to detect the header row automatically.

  • names: A list of column names to use when there is no header row. If the file contains a header row, you can override it by specifying custom column names.

  • index_col: Specifies a column (or multiple columns) to set as the DataFrame index.

  • usecols: Specifies which columns to load.

  • dtype: Defines the data type of columns.

  • engine: It specifies parser engine to use.

  • converters: This parameter takes a function or a dictionary of functions for converting values in specified columns.

  • true_values and false_values: Values to consider as True and False, in addition to case-insensitive True and False.

  • skiprows: Skips the specified number of rows at the start.

  • skipinitialspace: If True, skips spaces after delimiters.

  • skipfooter: Number of lines to skip at the bottom of the file.

  • keep_default_na: Include default NaN values for missing data.

  • na_filter: Detect missing value markers. Improves performance for files without missing data.

  • skip_blank_lines: Skip over blank lines when reading.

  • **kwargs: It takes many other parameters for fine tuning the parsing behavior.

Return Value

The Pandas read_csv() method returns a Pandas DataFrame containing the data from the CSV file.

Example: Reading a Simple CSV File

Here is a basic example demonstrating reading a simple CSV file using the pandas read_csv() method.

import pandas as pd

# Reading a CSV file
df = pd.read_csv('example_CSV_file.csv')
print("DataFrame from CSV File:")
print(df)

When we run above program, it produces following result −

DataFrame from CSV File:
Car Date_of_purchase
0 BMW 10-10-2024
1 Lexus 12-10-2024
2 Audi 17-10-2024
3 Mercedes 16-10-2024
4 Jaguar 19-10-2024
5 Bentley 22-10-2024

Example: Reading CSV File from an URL

This example reads the CSV data from an URL using the pandas read_csv() method.

import pandas as pd

url ="https://raw.githubusercontent.com/Opensourcefordatascience/Data-sets/master/blood_pressure.csv"

# read CSV into a Pandas DataFrame 
df = pd.read_csv(url)

print("DataFrame from CSV file using an URL:")
print(df.head(5))

Following is an output of the above code −

DataFrame from CSV file using an URL:
patient sex agegrp bp_before bp_after
0 1 Male 30-45 143 153
1 2 Male 30-45 163 170
2 3 Male 30-45 153 168
3 4 Male 30-45 153 142
4 5 Male 30-45 146 141

Example: Reading Selected Columns from a CSV File

This example demonstrates reading specific columns from a CSV file using the pandas read_csv() method with the usecols parameter.

import pandas as pd

url ="https://raw.githubusercontent.com/Opensourcefordatascience/Data-sets/master/blood_pressure.csv"

# read CSV into a Pandas DataFrame 
df = pd.read_csv(url, usecols=["agegrp", "bp_before"])

print("Reading Specific Columns from a CSV File:")
print(df.head(5))

While executing the above code we get the following output −

Reading Specific Columns from a CSV File:
agegrp bp_before
0 30-45 143
1 30-45 163
2 30-45 153
3 30-45 153
4 30-45 146

Example: Specifying Data Types for CSV Data

The read_csv() method allows you to specify the data type to the columns while reading data from a CSV file using the dtype parameter.

import pandas as pd

url = "https://raw.githubusercontent.com/pandas-dev/pandas/refs/heads/main/doc/data/baseball.csv"

# Reading CSV and parsing date columns
df = pd.read_csv(url, dtype={"id": "float", "team": "string"})

print("DataFrame with Specified Data Types:")
print(df.dtypes)

Following is an output of the above code −

DataFrame with Specified Data Types:
id               float64
player            object
year               int64
stint              int64
team      string[python]
lg                object
g                  int64
ab                 int64
r                  int64
h                  int64
X2b                int64
X3b                int64
hr                 int64
rbi              float64
sb               float64
cs               float64
bb                 int64
so               float64
ibb              float64
hbp              float64
sh               float64
sf               float64
gidp             float64
dtype: object
python_pandas_io_tool.htm
Advertisements