我有一个4Gb的CSV文件,其中包含严格的整数数据,我想读入pandas DataFrame。本机read_csv消耗所有RAM(64Gb),并因MemoryError而失败。对于显式dtype,它只需要花费很长时间(尝试了int和float类型)。在
所以,我写了我自己的读者:
def read_csv(fname):
import csv
reader = csv.reader(open(fname))
names = reader.next()[1:] # first row
dftype = np.float32
df = pd.DataFrame(0, dtype=dftype, columns=names, index=names)
for row in reader:
tag = row[0]
df.loc[tag] = np.array(row[1:], dtype=dftype)
return df
问题:如果dftype为np.int32(每行约20秒),所以我最终使用np.浮动64和return df.astype(np.int32)
(~4分钟)。我还尝试了Python转换([int/float(v)for v in row[1:]]),结果相同。在
为什么会这样?在
UPD:我在python2.7和3.5上也有相同的行为
我建议您对此使用numpy数组,例如:
我不知道为什么
int32
比float32
慢,但是DataFrame
按列存储数据,按df.loc[tag] = ...
设置每列的元素很慢。在如果您需要访问标签,可以使用xarray:
^{pr2}$更新:我的笔记本有16GB的RAM,所以我将用4倍(64GB/16GB=4)的DF测试它:
设置:
我们也将此数据框保存为羽毛格式:
^{pr2}$然后读回来:
从CSV文件中分块读取要慢得多,但仍然不能给我
MemoryError
:现在让我们显式地指定
dtype=np.int32
:测试HDF存储:
结论:
如果你有机会改变你的存储文件格式-无论如何不要使用CSV文件-使用HDF5(.h5)或羽毛格式。。。在
旧答案:
我只需使用原生熊猫read_csv()方法:
根据您的代码:
看起来您希望使用CSV文件中的第一列作为索引,因此:
index_col=0
相关问题 更多 >
编程相关推荐