Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas read_csv() Method



Theread_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 tosep parameter.

  • header: Specifies the row number to use as column names. Defaults toinfer, 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 Pandasread_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 pandasread_csv() method.

import pandas as pd# Reading a CSV filedf = 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:
CarDate_of_purchase
0BMW10-10-2024
1Lexus12-10-2024
2Audi17-10-2024
3Mercedes16-10-2024
4Jaguar19-10-2024
5Bentley22-10-2024

Example: Reading CSV File from an URL

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

import pandas as pdurl ="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:
patientsexagegrpbp_beforebp_after
01Male30-45143153
12Male30-45163170
23Male30-45153168
34Male30-45153142
45Male30-45146141

Example: Reading Selected Columns from a CSV File

This example demonstrates reading specific columns from a CSV file using the pandasread_csv() method with theusecols parameter.

import pandas as pdurl ="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:
agegrpbp_before
030-45143
130-45163
230-45153
330-45153
430-45146

Example: Specifying Data Types for CSV Data

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

import pandas as pdurl = "https://raw.githubusercontent.com/pandas-dev/pandas/refs/heads/main/doc/data/baseball.csv"# Reading CSV and parsing date columnsdf = 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               float64player            objectyear               int64stint              int64team      string[python]lg                objectg                  int64ab                 int64r                  int64h                  int64X2b                int64X3b                int64hr                 int64rbi              float64sb               float64cs               float64bb                 int64so               float64ibb              float64hbp              float64sh               float64sf               float64gidp             float64dtype: object
python_pandas_io_tool.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp