为什么scipy.savetxt('filename', (x,y))按行而不是按列保存数组?

1 投票
2 回答
2222 浏览
提问于 2025-04-17 19:53

我见过的大多数csv文件都是这样存储数组的:

#x y
0 10
1 11
2 12
 .
 .
 .

那么,为什么用 scipy.savetxt('scipy.txt', (x, y), header='x y', fmt='%g') 保存 x, y 会变成这样:

# x y
0 1 2 3 4 5
10 11 12 13 14 15

而用 scipy.savetxt('y.txt', y, header='y', fmt='%g') 保存时会得到:

# y
10
11
12
13
14
15

?

我必须使用 scipy.savetxt('common.txt', scipy.column_stack((x,y)), header='x y', fmt='%g') 才能得到更“常见”的格式。

注意,要从这个“常见”的文件中读取 xy

x, y = scipy.genfromtxt('common.txt', unpack=True)

xy = scipy.genfromtxt('common.txt')
x = xy[:,0]
y = xy[:,1]

xy = scipy.genfromtxt('common.txt', names=True)
x = xy['x']
y = xy['y']

甚至可以这样:

xy = scipy.genfromtxt('common.txt', names=True)
x, y = zip(*xy)
x, y = scipy.array(x), scipy.array(y)

从“scipy”文件中:

x, y = scipy.genfromtxt('scipy.txt')

而:

xy = scipy.genfromtxt('test.txt', names=True)

会引发错误,所以我们不能使用标题(不管怎样,这个标题真的有意义吗?)。

2 个回答

2

问题可能出在你保存的是一个(2,N)的数组,其实你想要的是一个(N,2)的数组。

import numpy as np
x = np.arange(10)
y = x + 2
print (x,y).shape
#(2,10)
z = np.array(zip(x,y))
print z.shape
#(10,2)

或者可以使用一个结构化数组来处理表头。

z = np.array(zip(x,y),dtype=[('x',int),('y',float)])
print z.shape
#(10,)
np.savetxt('tmp.txt',z)

这样就能得到你想要的结果。

2

np.savetxt 这个函数可以把一维数组写成每行一个元素的格式。

而对于二维数组,它会把每一行写成一行。

这就是为什么当你用 scipy.savetxt('y.txt', y...) 时,会得到一列很长的数据。还有,numpy和scipy把 (x, y) 视为一维的元组,而不是二维数组。这就是你得到的结果是

0 1 2 3 4 5
10 11 12 13 14 15

的原因。

所以,如果你想得到想要的输出,就需要传入一个二维数组。正如你提到的,使用 np.column_stack 是最简单的方法:

import numpy as np
np.savetxt(filename, np.column_stack((x,y)), fmt='%g')

要把数据读回到 xy 变量中,可以使用 unpack=True 这个参数:

x, y = np.genfromtxt(filename, unpack=True)

撰写回答