动态附加N维数组 [英] dynamically append N-dimensional array

查看:101
本文介绍了动态附加N维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果每个数组的形状为(1000,2,100),则易于使用

If each array has the shape (1000, 2, 100), it is easy to use

con = np.concatenate((array_A, array_B))

将它们串联起来,因此con的形状为(2000,2,100).

to concatenate them, thus con has the shape (2000, 2, 100).

我想在函数中动态附加或连接"con".该步骤描述如下:

I want to dynamically append or concatenate "con" in a function. The step is described as following:

First, read data from the first file and process data to generate an array.

Secondly, read date from the second file and append generated array into the first array

....

def arrayappend():
     for i in range(n):
         #read data from file_0 to file_n-1
         data = read(file_i)
         #data processing to generate an array with shape (1000, 2, 100)
         con = function(data)
         # append con

推荐答案

假设所有文件都产生相同的形状对象,并且您想在第一维上将它们连接起来,则有几种选择:

Assuming all your files produce the same shape objects and you want to join them on the 1st dimension, there are several options:

 alist = []
 for f in files:
    data = foo(f)
    alist.append(f)
 arr = np.concatenate(alist, axis=0)

concatenate列出一个列表.如果要添加新轴(np.array(alist)np.stack等),会有一些变化.

concatenate takes a list. There are variations if you want to add a new axis (np.array(alist), np.stack etc).

追加到列表很快,因为这只是意味着将指针添加到data对象. concatenate从组件创建一个新数组;它已编译,但仍然相对较慢.

Append to a list is fast, since it just means adding a pointer to the data object. concatenate creates a new array from the components; it's compiled but still relatively slower.

如果您必须/想要在每个阶段创建一个新数组,您可以编写:

If you must/want to make a new array at each stage you could write:

 arr = function(files[0])
 for f in files[1:]:
     data = foo(f)
     arr = np.concatenate((arr, data), axis=0)

这可能会更慢,但是,如果文件加载步骤足够慢,您可能不会注意到差异.

This probably is slower, though, if the file loading step is slow enough you might not notice a difference.

小心一点,您也许可以从arr = np.zeros((0,2,100))开始并读取循环中的所有文件.您必须确保初始的空"数组具有兼容的形状.新用户经常对此有疑问.

With care you might be able start with arr = np.zeros((0,2,100)) and read all files in the loop. You have to make sure the initial 'empty' array has a compatible shape. New users often have problems with this.

这篇关于动态附加N维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆