如何将元素追加到numpy数组
问题描述:
我想等效于在Numpy中递归地在python列表中添加元素,如以下代码所示
I want to do the equivalent to adding elements in a python list recursively in Numpy, As in the following code
matrix = open('workfile', 'w')
A = []
for row in matrix:
A.append(row)
print A
我尝试了以下操作:
matrix = open('workfile', 'w')
A = np.array([])
for row in matrix:
A = numpy.append(row)
print A
它不返回所需的输出,如列表中所示.
It does not return the desired output, as in the list.
编辑此为示例代码:
mat = scipy.io.loadmat('file.mat')
var1 = mat['data1']
A = np.array([])
for row in var1:
np.append(A, row)
print A
这只是我想做的最简单的情况,但是循环中有更多的数据处理,我这样写,这样例子很清楚.
This is just the simplest case of what I want to do, but there is more data processing in the loop, I am putting it this way so the example is clear.
答
您需要将数组A传递给Numpy.
You need to pass the array, A, to Numpy.
matrix = open('workfile', 'w')
A = np.array([])
for row in matrix:
A = numpy.append(A, row)
print A
但是,直接从文件加载可能是一个更好的解决方案.
However, loading from the files directly is probably a nicer solution.