6

使用Python处理大型CSV文件

 1 year ago
source link: https://www.51cto.com/article/770141.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用Python处理大型CSV文件

作者:ant 2023-10-17 16:24:27

本教程将详细介绍如何使用Python和pandas库来选择性地读取和处理大型CSV文件中的字段,以避免内存不足的问题。

使用Python处理大型CSV文件

处理大型CSV文件时,可能会遇到内存限制等问题。一种常见的解决方案是使用Python的pandas库,它允许我们选择性地读取文件的特定部分,而不是一次性加载整个文件,这在面对大数据集时尤为重要。

本教程将详细介绍如何使用Python和pandas库来选择性地读取和处理大型CSV文件中的字段,以避免内存不足的问题。

1.选择性读取字段

在此步骤中,我们通过usecols参数选择性地读取感兴趣的列,以减轻内存负担。

import pandas as pd


# 指定CSV文件的路径
csv_file_path = "<文件路径>"


# 指定需要提取的字段列名
selected_columns = ['unified_code', 'reg_addr']


# 使用pd.read_csv()读取指定列的数据
data = pd.read_csv(csv_file_path, usecols=selected_columns)


# 显示读取的数据
print(data.head())


# 保存读取的数据到新的CSV文件中
csv_output_file_path = "<输出文件路径>"
data.to_csv(csv_output_file_path, index=False)


print("数据已保存为CSV文件:", csv_output_file_path)

2.数据合并

我们有两个CSV文件,需要基于'unified_code'字段进行合并。pandas的merge函数允许我们进行这样的操作。

import pandas as pd



# 指定两个CSV文件的路径

csv_file1_path = "<文件1路径>"

csv_file2_path = "<文件2路径>"



# 读取两个CSV文件

data1 = pd.read_csv(csv_file1_path)

data2 = pd.read_csv(csv_file2_path)



# 基于'unified_code'字段合并数据

merged_data = data1.merge(data2, on='unified_code', how='inner')



# 显示合并后的数据

print(merged_data.head())



# 保存合并后的数据到新的CSV文件中

merged_csv_file_path = "合并后的数据.csv"

merged_data.to_csv(merged_csv_file_path, index=False)



print("匹配成功的数据已保存为CSV文件:", merged_csv_file_path)

3.生成唯一ID并保存数据

最后,我们为每行数据生成一个唯一的ID,对数据进行筛选,并将结果保存到新的CSV文件中。

import pandas as pd



# 指定CSV文件的路径

csv_file_path = "合并后的数据.csv"



# 读取CSV文件

data = pd.read_csv(csv_file_path)



# 为每一行生成唯一的ID

data['ID'] = range(1, len(data) + 1)



# 选择性保留字段

selected_columns = ['ID', 'unified_code', 'reg_addr']

data = data[selected_columns]



# 保存清理后的数据到新的CSV文件中

output_csv_file_path = "clean.csv"

data.to_csv(output_csv_file_path, index=False)



print("数据已保存为CSV文件:", output_csv_file_path)

本教程演示了如何使用Python和pandas库对大型CSV文件进行选择性读取、合并和保存,以避免内存不足的问题。这种方法在处理大数据集时非常有用,能够显著提高数据处理的效率。

95fc31d10816ab151db492ea82491c38067fd9.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK