Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.ead_csv() function

Pandas pd.ead_csv() function

Python math Module Common Pandas functions


read_csv() is the most commonly used data-reading function in the pandas library, used to read data from a CSV (comma-separated values) file and create a DataFrame.

A CSV file is a simple and widely used data exchange format that stores tabular data as plain text, with each line representing a record and fields separated by commas.read_csv() can intelligently parse CSV files, automatically detect column names and data types, and handle various delimiters and encoding issues.


Basic syntax and parameters

Syntax format



pandas.read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer',

                names=None, index_col=None, usecols=None, dtype=None,

                skiprows=None, nrows=None, na_values=None, ...)

Parameter Description

Parameters Type Description Default value
filepath_or_buffer str, path object, or file-like object the path, URL, or file object of the CSV file Required
sep str the field delimiter; the CSV default is a comma ','
header int, list of int, 'infer' the row number to use as column names; 0 means the first row 'infer'
names list-like a custom list of column names None
index_col int, str, list of int, list of str, False Column used as the row index None
usecols list-like, callable read only the specified columns None
dtype dict specify column data types, e.g., {'a': np.float64} None
skiprows list-like, int skip the specified rows None
nrows int read only the first n rows None
na_values scalar, str, list-like, dict values to be recognized as NA/NaN None
encoding str the file encoding, e.g., 'utf-8' None

Return Value


Example

Through the following examples, fully master read_csv() its various usages.

Example 1: read a local CSV file

First create a simple CSV file, then use read_csv() to read it.

Example

import

pandas

as

pd

Create a sample CSV file

First write some test data

data

=

"""name,age,city,salary
Tom,28,Beijing,8000
Jerry,35,Shanghai,12000
Mike,42,Guangzhou,15000
Lucy,26,Shenzhen,7000
"""

Write the data to a file (in practice you can read an existing file directly)

with

open

(

'employees.csv'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

data

)

Read the CSV file using read_csv

filepath_or_buffer: file path (required)

df

=

pd.

read_csv

(

'employees.csv'

)

View the reading result

print

(

"DataFrame read:"

)

print

(

df

)

print

(

"ndata types:"

)

print

(

df.

dtypes

)

print

(

"ncolumn names:"

,

df.

columns

.

tolist

(

)

)

Expected output:



读取的 DataFrame:

    name  age       city  salary

0    Tom   28    Beijing    8000

1  Jerry   35   Shanghai   12000

2   Mike   42  Guangzhou   15000

3   Lucy   26  Shenzhen    7000



Data type:

name      object

age        int64

city      object

salary    int64



列名: ['name', 'age', 'city', 'salary']

Code analysis:

Example 2: custom column names and selecting specific columns

In real work, we may need to customize column names or read only some columns to improve performance.

Example

import

pandas

as

pd

Create test data

data

=

"""name,age,city,salary,department
Tom,28,Beijing,8000,IT
Jerry,35,Shanghai,12000,HR
Mike,42,Guangzhou,15000,Sales
Lucy,26,Shenzhen,7000,IT
"""

with

open

(

'employees2.csv'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

data

)

Example 2a: custom column names

The names parameter specifies new column names and overrides those in the original file

df_custom

=

pd.

read_csv

(

'employees2.csv'

,

names

=

[

'Name'

,

'Age'

,

'City'

,

'Salary'

,

'Department'

]

,

header

=

0

)

print

(

"DataFrame with custom column names:"

)

print

(

df_custom

)

print

(

)

Example 2b: read only the specified columns

The usecols parameter lets you specify which columns to read, improving performance

df_partial

=

pd.

read_csv

(

'employees2.csv'

,

usecols

=

[

'name'

,

'salary'

]

)

print

(

"only some columns read:"

)

print

(

df_partial

)

print

(

)

Example 2c: use index_col to specify an index column

df_indexed

=

pd.

read_csv

(

'employees2.csv'

,

index_col

=

'name'

)

print

(

"set name as the index:"

)

print

(

df_indexed

)

Expected output:



自定义列名后的 DataFrame:

    姓名  年龄       城市    薪资     部门

0   Tom   28    Beijing   8000      IT

1  Jerry   35   Shanghai  12000      HR

2   Mike   42  Guangzhou  15000   Sales

3   Lucy   26   Shenzhen   7000      IT



# Only read a subset of columns:

   name  salary

0    Tom    8000

1  Jerry   12000

2   Mike   15000

3    Lucy    7000



Set name as index:

      age       city  salary department

name

Tom     28    Beijing    8000         IT

Jerry  35   Shanghai   12000         HR

Mike   42  Guangzhou   15000       Sales

Lucy   26   Shenzhen    7000         IT

Code analysis:

Example 3: handling special data and improving missing-value handling

A CSV file may contain missing values, use special delimiters, or require skipping certain rows.

Example

import

pandas

as

pd

Create a CSV file containing special data

Use a semicolon as the delimiter, including missing values and NA values

data

=

"""name;age;city;salary
Tom;28;Beijing;8000
Jerry;;Shanghai;12000
Mike;42;Guangzhou;
Lucy;26;NA;7000
"""

with

open

(

'employees3.csv'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

data

)

Example 3a: read a semicolon-delimited file

df_semicolon

=

pd.

read_csv

(

'employees3.csv'

,

sep

=

';'

)

print

(

"using the semicolon delimiter:"

)

print

(

df_semicolon

)

print

(

"missing value statistics:"

)

print

(

df_semicolon.

isnull

(

)

)

print

(

)

Example 3b: specify which values are treated as missing

df_na

=

pd.

read_csv

(

'employees3.csv'

,

sep

=

';'

,

na_values

=

[

'NA'

,

'missing'

]

)

print

(

"after custom NA values:"

)

print

(

df_na

)

print

(

)

Example 3c: skip rows and limit the number of rows read

If the first few lines of the file are comments, you can skip them

data_with_comment

=

"""# This is an employee data file

Created: 2024-01-01

name;age;city;salary
Tom;28;Beijing;8000
Jerry;35;Shanghai;12000
Mike;42;Guangzhou;15000
Lucy;26;Shenzhen;7000
"""

with

open

(

'employees4.csv'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

data_with_comment

)

skiprows skips the first two lines (comment lines)

df_skip

=

pd.

read_csv

(

'employees4.csv'

,

sep

=

';'

,

skiprows

=

2

)

print

(

"after skipping comment lines:"

)

print

(

df_skip

)

print

(

)

nrows reads only the first 3 rows

df_nrows

=

pd.

read_csv

(

'employees4.csv'

,

sep

=

';'

,

skiprows

=

2

,

nrows

=

3

)

print

(

"only the first 3 rows read:"

)

print

(

df_nrows

)

Expected output:



Using semicolon separator:

    name  age       city   salary

0    Tom   28.0    Beijing   8000.0

1  Jerry   NaN   Shanghai  12000.0

2    NaN  42.0   Guangzhou      NaN

3  Lucy  26.0         NA    7000.0



Missing value statistics:

    name    age   city  salary

0  False  False  False   False

1  False   True  False   False

2   True  False  False    True

3  False  False   False  False



After customizing NA values:

    name  age       city   salary

0    Tom  28.0    Beijing   8000.0

1  Jerry   NaN   Shanghai  12000.0

2   NaN  42.0   Guangzhou      NaN

3  Lucy  26.0         NaN   7000.0



After skipping comment lines:

    name  age       city  salary

0    Tom   28   Beijing    8000

1  Jerry  35  Shanghai   12000

  42  Guangzhou   15000

2   Mike

3   Lucy   26   Shenzhen    7000



Only read the first 3 lines:

    name  age       city  salary

0    Tom   28   Beijing    800本地

1  Jerry  35   Shanghai   12000

2   Mike   42  Guangzhou   15000

Code analysis:


Notes


Summary

read_csv() is the most basic and most important data-reading function in pandas. It is powerful, supporting multiple delimiters, custom column names, index settings, missing-value handling, and other advanced features.

In real data analysis work, mastering read_csv() and its various parameters lets you efficiently handle CSV files in various formats, laying a solid foundation for subsequent data cleaning and analysis. Readers are encouraged to practice more and master these common parameters.

Python math Module Common Pandas functions