要求:
这是我的代码:
def __init__(self):
self.data = []
def update(self, row):
self.data.append(row)
def finalize(self):
dx = np.array(self.data)
Run Code Online (Sandbox Code Playgroud)
我试过的其他事情包括以下代码......但这是waaaaay慢.
def class A:
def __init__(self):
self.data = np.array([])
def update(self, row):
np.append(self.data, row)
def finalize(self):
dx = np.reshape(self.data, size=(self.data.shape[0]/5, 5))
Run Code Online (Sandbox Code Playgroud)
以下是如何调用此示意图的示意图:
for i in range(500000):
ax = A()
for j in range(200):
ax.update([1,2,3,4,5])
ax.finalize()
# some processing on ax
Run Code Online (Sandbox Code Playgroud) 我刚刚在内存中试验了python数据结构的大小.我写了以下片段:
import sys
lst1=[]
lst1.append(1)
lst2=[1]
print(sys.getsizeof(lst1), sys.getsizeof(lst2))
Run Code Online (Sandbox Code Playgroud)
我在以下配置上测试了代码:
52 40所以lst1有52个字节,lst2有40个字节.48 3248 36任何人都可以向我解释为什么两个尺寸不同虽然两个都是包含1的列表?
在getsizeof函数的python文档中,我发现了以下内容:...adds an additional garbage collector overhead if the object is managed by the garbage collector.在我的小例子中可能是这种情况吗?
我想从iterable中创建一个numpy数组,它产生值的元组,例如数据库查询.
像这样:
data = db.execute('SELECT col1, col2, col3, col4 FROM data')
A = np.array(list(data))
Run Code Online (Sandbox Code Playgroud)
有没有更快的方法这样做,而不首先将迭代转换为列表?
我有很多文件,每个文件都被读取为 shape 的矩阵(n, 1000),其中 n 可能因文件而异。
我想将它们全部连接成一个大的 Numpy 数组。我目前这样做:
dataset = np.zeros((100, 1000))
for f in glob.glob('*.png'):
x = read_as_numpyarray(f) # custom function; x is a matrix of shape (n, 1000)
dataset = np.vstack((dataset, x))
Run Code Online (Sandbox Code Playgroud)
但它效率低下,因为我dataset通过将现有数组与读取的下一个文件堆叠起来多次重新定义。
如何使用 Numpy 以更好的方式做到这一点,避免整个数据集在内存中多次重写?
注意:最终的大 Numpy 数组可能需要 10 GB。