【问题标题】:Adding 2d Numy array to 1d Numpy Array将 2d Numpy 数组添加到 1d Numpy 数组
【发布时间】: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_pointend_point进行更改
  • @DaniMesejo 好的,我更新它只是为了清除它,感谢您注意到这一点
  • 附加到数组不会像列表那样摊销。这样你会浪费更多的内存。您最好的选择是第一个选项。
  • 显示一个完整的minimal reproducible example,带有随机数或其他东西。你所做的大部分陈述都是无稽之谈。您的数据已经在内存中,并且您没有显示实际“吃掉你的内存”或“条件”是什么

标签: python arrays numpy


【解决方案1】:

Numpy 数组之所以如此高效,是因为它们具有固定的大小和类型。因此,“附加”到一个数组是非常缓慢和消耗的,因为一个新的数组一直在创建。如果您事先知道您有多少样本(例如 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 的众多转换功能可能会更快、更快地解决。

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

【讨论】:

  • 我相信这是一个不错的技巧。但是,将 np.float64 更改为 np.object 在这里起着重要作用,是否有某种方法可以指定每列的数据类型,因为我在某些列中有文本数据?也许你有别的想法?
  • 我认为这回答了我的问题here
  • 我在不知道大代码的情况下写了答案 - np.float64 只是一个猜测。如果你正在处理字符串,你当然需要 np.object 。但是有一个原因,为什么它被称为“Num”Py 而不是“Object”Py 或“Str”Py。如果你有混合类型,我会完全避免使用 NumPy 数组 - 列表更好。
猜你喜欢
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2022-09-23
  • 2022-01-09
  • 2013-08-28
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多