python - 如何将元素附加到 numpy 数组

标签 python numpy

我想做的相当于在 Numpy 中递归地在 python 列表中添加元素,如以下代码所示

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

它不会像列表中那样返回所需的输出。

编辑这是示例代码:

mat = scipy.io.loadmat('file.mat')
var1 = mat['data1']
A = np.array([])
for row in var1:
    np.append(A, row)

print A

这只是我想要做的最简单的情况,但是循环中有更多的数据处理,我这样说是为了让例子更清楚。

最佳答案

您需要将数组 A 传递给 Numpy。

matrix = open('workfile', 'w')
A = np.array([])
for row in matrix:
    A = numpy.append(A, row)

print A

但是,直接从文件加载可能是更好的解决方案。

关于python - 如何将元素附加到 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28943887/

相关文章:

python - 使用 ssl 在 Freebsd 11 上安装 Python 3.7

python - 将 html 解码字符串写入文件和将 html 二进制数据直接写入文件之间有什么区别?

python - 通过 DataFrame 在 Python Pandas Group 上执行数学运算

python - 当我尝试在 pyqt5 程序中运行语音识别时崩溃了

python - 限时终止Python进程

python - 灰度图像至 3 个 channel

python-3.x - python3-numpy : Appending to a file using numpy savetxt

python - 提取numpy矩阵的上三角或下三角部分

python - TemplateDoesNotExist at/polls/- 在 Django 教程中

python - 如何并行化计算?