Home >Backend Development >Python Tutorial >Sharing practical tips for reading CSV data in Python

Sharing practical tips for reading CSV data in Python

PHPz
PHPzOriginal
2024-04-04 10:54:02719browse

There are two ways to read CSV data in Python: the built-in csv module, which is suitable for small CSV files and iterates data by row; the Pandas library provides the read_csv() function, which can easily load CSV data into a DataFrame for processing. .

Sharing practical tips for reading CSV data in Python

Sharing practical tips for reading CSV data in Python

In data science and machine learning, we often need to read CSV data from CSV ( comma separated values) file. Python provides several built-in functions and libraries for this purpose. This tutorial will explore different ways to read CSV data in Python and provide practical examples.

Built-in functions

For small CSV files, we can use the built-in csv module. It provides a [reader()](https://docs.python.org/3/library/csv.html#csv.reader) function for iterating CSV data row by row.

import csv

with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        # 处理每一行数据

Pandas Library

Pandas is a popular library for data analysis and manipulation. It provides a [read_csv()](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html) function that can easily load CSV data into a DataFrame . DataFrame is a table-like data structure that is easy to process and manipulate.

import pandas as pd

df = pd.read_csv('data.csv')
# 访问 DataFrame 中的数据

Practical case

Consider a CSV file named data.csv, which contains the following data:

name,age
John,25
Jane,30

Read data using built-in functions:

import csv

with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Output:

['name', 'age']
['John', '25']
['Jane', '30']

Read data using Pandas library:

import pandas as pd

df = pd.read_csv('data.csv')
print(df)

Output :

   name  age
0  John   25
1  Jane   30

Conclusion

We can easily read data from CSV files by using built-in functions or Pandas library. These techniques are useful when working with both small and large CSV files. The method chosen depends on the size and complexity of the particular data set.

The above is the detailed content of Sharing practical tips for reading CSV data in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn