numpy.savetxt保存新行的每个元素?

Ani*_*dey 3 python arrays numpy

with file("features.txt", "w") as outfile:
    # temp_array is an array of shape (500L,)
    np.savetxt(outfile, X=np.array(temp_array, dtype='uint8'), delimiter=",")
Run Code Online (Sandbox Code Playgroud)

我使用上面的语法在文本文件中存储大约10,000个数组,但我注意到所有元素都存储在不同的行上.

如果我使用加载文本文件numpy.loadtxt,我将得到一个数组而不是矩阵.

我知道可以numpy.reshape在加载的数组上使用它将其转换为矩阵,但在我的应用程序中,加载它的用户将无法知道行数.

如何解决这个问题?

jme*_*jme 6

如果给出np.savetxt一维数组,它会将所述数组视为一列,并在新行上写入每个条目.我可以想到两种解决方法.第一种是在数组中添加一个新轴,使其成为行向量:

x = np.arange(5)
np.savetxt('test.txt', x[np.newaxis], fmt='%d', delimiter=',')
Run Code Online (Sandbox Code Playgroud)

第二种方法是告诉np.savetxt使用除\n换行之外的其他字符.例如,一个空格:

np.savetxt('test.txt', x, fmt='%d', newline=' ', delimiter=',')
Run Code Online (Sandbox Code Playgroud)

这两个都会导致文件看起来像

0 1 2 3 4
Run Code Online (Sandbox Code Playgroud)