在 Python 中,操作 CSV文件通常使用 csv 模块和 pandas 库,这两个工具提供了丰富的功能,可以方便地读取、写入和处理CSV 文件
csv 模块是 Python 标准库的一部分,提供了读取和写入 CSV 文件的基本功能
主要功能
import csv
# 读取 CSV 文件
with open('example.csv', mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
import csv
# 读取 CSV 文件并转换为字典
with open('example.csv', mode='r', newline='', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
import csv
# 数据
data = [
['Name', 'Age'],
['Alice', 25],
['Bob', 30]
]
# 写入 CSV 文件
with open('example.csv', mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data)
import csv
# 数据
data = [
{'Name': 'Alice', 'Age': 25},
{'Name': 'Bob', 'Age': 30}
]
# 写入 CSV 文件
with open('example.csv', mode='w', newline='', encoding='utf-8') as file:
fieldnames = ['Name', 'Age']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
pandas 是一个强大的数据分析库,支持读取和写入多种数据格式,包括 CSV 文件,pandas提供了丰富的数据处理功能,如数据筛选、排序、聚合等
主要功能
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('example.csv')
print(df)
import pandas as pd
# 读取特定列
df = pd.read_csv('example.csv', usecols=['Name', 'Age'])
print(df)
import pandas as pd
# 数据
data = {
'Name': ['Alice', 'Bob'],
'Age': [25, 30]
}
# 创建 DataFrame
df = pd.DataFrame(data)
# 写入 CSV 文件
df.to_csv('example.csv', index=False)
import pandas as pd
# 数据
data = {
'Name': ['Alice', 'Bob'],
'Age': [25, 30]
}
# 创建 DataFrame
df = pd.DataFrame(data)
# 写入 CSV 文件并指定分隔符
df.to_csv('example.csv', index=False, sep=';')
对于非常大的 CSV 文件,可以使用 pandas 的 read_csv 函数的 chunksize 参数分块
import pandas as pd
# 分块读取 CSV 文件
chunksize = 10000
chunks = []
for chunk in pd.read_csv('large_example.csv', chunksize=chunksize):
# 处理每个 chunk
processed_chunk = chunk[chunk['Age'] > 25] # 例如,筛选年龄大于 25 的行
chunks.append(processed_chunk)
# 合并所有 chunk
df = pd.concat(chunks)
print(df)
pandas 提供了丰富的数据清洗功能,如删除缺失值、替换值、重命名列等
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('example.csv')
# 删除缺失值
df.dropna(inplace=True)
# 替换值
df['Age'].replace(25, 26, inplace=True)
# 重命名列
df.rename(columns={'Name': 'FullName'}, inplace=True)
print(df)