将2d Numpy array添加到1d Numpy array



我有一个python列表,每个元素是一个2d Numpy数组,大小为(20, 22)。我需要将列表转换为numpy数组,但执行np.array(my_list)实际上是在消耗RAM,np.asarray(my_list)也是如此。

列表有大约7M个样本,我在想,而不是将我的列表转换为numpy数组,让我从一个numpy数组开始,并不断添加另一个2d numpy数组。

我无法使用numpy找到这样做的方法,我的目标是像这样开始:

numpy_array = np.array([])
df_values = df.to_numpy() # faster than df.values
for x in df_values:
if condition:
start_point += 20
end_point += 20
features = df_values[start_point:end_point] # 20 rows, 22 columns
np.append(numpy_array, features)

正如您在上面看到的,在每个循环之后,numpy_array的大小应该像这样改变:

first iteration: (1, 20, 22) 
second iteration: (2, 20, 22) 
third iteration: (3, 20, 22) 
N iteration: (N, 20, 22) 

更新:

这是我的完整代码,

def get_X(df_values):
x = [] #np.array([], dtype=np.object)
y = [] # np.array([], dtype=int32)
counter = 0
start_point = 20
previous_ticker = None
index = 0
time_1 = time.time()
df_length = len(df_values)
for row in tqdm(df_values):
if 0 <= start_point < df_length:
ticker = df_values[start_point][0]
flag = row[30]
if index == 0: previous_ticker = ticker
if ticker != previous_ticker:
counter += 20 
start_point += 20
previous_ticker = ticker
features = df_values[counter:start_point]
x.append(features)
y.append(flag)
# np.append(x, features)
# np.append(y, flag)
counter += 1
start_point += 1
index += 1
else:
break
print("Time to finish the loop", time.time()-time_1)
return x, y

x, y = get_X(df.to_numpy())

Numpy数组非常高效,因为它们有固定的大小和类型。因此,"appending"到一个数组是非常缓慢和消耗的,因为一个新的数组是创建的所有时间。如果你事先知道你有多少样本(例如7000000),最好的方法是:

N = 7000000
# Make complete array with NaN's
features = np.empty(size=(N, 20, 22), dtype=np.float64) * np.NaN
for whatever:
...
features[counter:start_point] = ...

当使用循环时,应该是最快和最节省内存的方式。然而,这看起来像是将数据帧转换为3D数组,使用pandas的许多转换功能可以更快地解决这个问题。

如果你不知道最终的尺寸,在较大的尺寸上出错,然后复制一次到较小的(正确的)尺寸上。

最新更新