Python 如何将元素附加到 numpy 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28943887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append elements to a numpy array
提问by user3025898
I want to do the equivalent to adding elements in a python list recursively in Numpy, As in the following code
我想做相当于在 Numpy 中递归地在 python 列表中添加元素,如下面的代码
matrix = open('workfile', 'w')
A = []
for row in matrix:
A.append(row)
print A
I have tried the following:
我尝试了以下方法:
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.
它不会返回所需的输出,如列表中所示。
Edit this is the sample code:
编辑这是示例代码:
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.
这只是我想要做的最简单的情况,但是循环中有更多的数据处理,我是这样说的,所以例子很清楚。
采纳答案by user3590169
You need to pass the array, A, to Numpy.
您需要将数组 A 传递给 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.
但是,直接从文件加载可能是一个更好的解决方案。