酸洗numpy数组或列表时的pickle文件大小

Jav*_*ier 8 python arrays numpy list pickle

我有成千上万的长整数列表(8640).例如:

type(l1)
tuple

len(l1)
2

l1[0][:10]
[0, 31, 23, 0, 0, 0, 0, 0, 0, 0]

l1[1][:10]
[0, 0, 11, 16, 24, 0, 0, 0, 0, 0] 
Run Code Online (Sandbox Code Playgroud)

我正在"挑选"元组,似乎当元组是列表时,pickle文件比numpy数组更轻.我不是python的新手,但绝不是我是专家,我真的不知道如何为不同类型的对象管理内存.我希望numpy数组更轻,但这是我在挑选不同类型的对象时获得的:

#elements in the tuple as a numpy array
l2 = [np.asarray(l1[i]) for i in range(len(l1))]
l2
[array([ 0, 31, 23, ...,  2,  0,  0]), array([ 0,  0, 11, ...,  1,  0,  0])]

#integers in the array are small enough to be saved in two bytes
l3 = [np.asarray(l1[i], dtype='u2') for i in range(len(l1))]
l3
[array([ 0, 31, 23, ...,  2,  0,  0], dtype=uint16),
 array([ 0,  0, 11, ...,  1,  0,  0], dtype=uint16)]

#the original tuple of lists
with open('file1.pkl','w') as f:
     pickle.dump(l1, f)

#tuple of numpy arrays
with open('file2.pkl','w') as f:
    pickle.dump(l2, f)

#tuple of numpy arrays with integers as unsigned 2 bytes
with open('file3.pkl','w') as f:
    pickle.dump(l3, f)
Run Code Online (Sandbox Code Playgroud)

当我检查文件的大小时:

 $du -h file1.pkl
  72K   file1.pkl

 $du -h file2.pkl
  540K  file2.pkl

 $du -h file3.pkl
 136K   file3.pkl
Run Code Online (Sandbox Code Playgroud)

因此,即使将整数保存在两个字节中,file1也比file3轻.我更喜欢使用数组,因为解压缩数组(并处理它们)比列表快得多.但是,我将存储大量这些元组(在pandas数据框中),所以我也想尽可能优化内存.

我需要这个工作的方式是,给定一个元组列表:

#list of pickle objects from pickle.dumps
tpl_pkl = [pickle.dumps(listoftuples[i]) for i in xrange(len(listoftuples))]

#existing pandas data frame. Inserting new column 
df['tuples'] = tpl_pkl
Run Code Online (Sandbox Code Playgroud)

总的来说,我的问题是:numpy数组在将它们腌制成文件后占用的空间是否比列表更多?

也许如果我理解我能找到存储数组的最佳方式的原因.

在此先感谢您的时间.

hol*_*web 3

如果你想在磁盘上存储 numpy 数组,你pickle根本不应该使用。究numpy.save()其亲。

如果您正在使用,pandas那么它也有自己的方法。您可能需要查阅本文或此问题的答案以获得更好的技术。