【发布时间】:2021-10-04 21:30:19
【问题描述】:
我有一个 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())
【问题讨论】:
-
features不是总是同一个数组吗? -
@DaniMesejo 正在根据
start_point和end_point进行更改 -
@DaniMesejo 好的,我更新它只是为了清除它,感谢您注意到这一点
-
附加到数组不会像列表那样摊销。这样你会浪费更多的内存。您最好的选择是第一个选项。
-
显示一个完整的minimal reproducible example,带有随机数或其他东西。你所做的大部分陈述都是无稽之谈。您的数据已经在内存中,并且您没有显示实际“吃掉你的内存”或“条件”是什么