首页 > 解决方案 > 使用 Pandas 在现有的大型 CSV 文件中插入一列,而不会消耗太多 RAM

问题描述

我正在使用大小超过 2GB 的 Python Pandas 读取一个大型 CSV 文件。最终,我试图做的是在文件的第一个索引中添加一个“日期”列,将文件从 364 行和大约 360,000 列转换为只有三列(“日期”、“位置”和“数据”)有很多很多行。然后,这将被写入一个新转置的 CSV 文件。

对于更多的上下文,364 行中的每一行都代表一年中的每一天。对于每一天(每一行),都有成千上万个站点位置(这些是列),每个位置都包含在该位置进行的测量。

该文件现在看起来像这样:

Index     Location #1    Location #2    Location #359000...

0         Measurement    Measurement    Measurement
1         Measurement    Measurement    Measurement
2         Measurement    Measurement    Measurement
3         Measurement    Measurement    Measurement
364...    Measurement    Measurement    Measurement

我试图通过使用 Pandas 的“date_range”函数创建一个日期列,然后将该列插入到一个新的数据框中来添加新列。

import pandas as pd

#read in csv file
df = pd.read_csv('Path to file')

#define 'Date' column
date_col = pd.date_range(start='1/1/2001', periods=364, freq='D')

#add 'Date' column at the 0th index to be the first column
df1 = df.insert(0, 'Date', date_col)

#rearrange rows to columns and index by date
long_df = df.set_index('Date').unstack().to_frame('Data').swaplevel().sort_index

#write out to new csv file, specifying two other columns via index label
long_df.to_csv('Transposed_csv_file', index=True, index_label=['Location', 'Data'])

我正在寻找的输出是一个转置的 CSV 文件,如下所示:

Date        Location          Data

1/1/2001    Location No. 1    Measurement 1
1/1/2001    Location No. 2    Measurement 2
1/1/2001    Location No. 3    Measurement 3

一旦 1 月 1 日结束,它将移至 1 月 2 日,如下所示:

1/2/2001    Location No. 1    Measurement 1
1/2/2001    Location No. 2    Measurement 2
1/2/2001    Location No. 3    Measurement 3

这种模式将一直重复到 2001 年 12 月 31 日结束。

三列——多行。基本上,我正在从 X 位置转换为 Y 位置格式的 CSV 文件。

现在发生的情况是,当我尝试运行这些代码行时,我通过任务管理器注意到我的内存正在慢慢被消耗,达到 96% 以上。我有 32GB 的内存。Pandas 读取一个 2GB 的 CSV 文件并输出另一个大的转置文件是不可能消耗那么多内存的。我不确定我做错了什么,或者是否有更好的方法可以用来实现我想要的结果。谢谢您的帮助。

标签: pythondatabasepandasformatfilesize

解决方案


推荐阅读