我见过的大多数 csv 文件都是这样存储数组的:
#x y
0 10
1 11
2 12
.
.
.
那么,为什么 scipy.savetxt('scipy.txt', (x, y), header='x y', fmt='%g')
会存储 x,你
像这样:
# 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')
来获得更“通用”的格式。
注意从“普通”文件读取x
和y
:
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)
会引发错误,所以我们不能使用 header (无论如何,这个 header 有实际意义吗?)。
最佳答案
np.savetxt
写入每行一个元素的一维数组。
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')
要将数据读回x
和y
变量,请使用unpack=True
参数:
x, y = np.genfromtxt(filename, unpack=True)
关于python - 为什么 scipy.savetxt ('filename' , (x,y)) 按行而不是按列保存数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550210/