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

标签 python numpy scipy

我见过的大多数 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') 来获得更“通用”的格式。

注意从“普通”文件读取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)

会引发错误,所以我们不能使用 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')

要将数据读回xy 变量,请使用unpack=True 参数:

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

关于python - 为什么 scipy.savetxt ('filename' , (x,y)) 按行而不是按列保存数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550210/

相关文章:

python - 模拟对象库 ANY 未按预期工作

python - 在不运行Python包的情况下检查它的内容?

python - 将 Python 对象传递给 C 模块

python - 滑动窗口操作的 Numpy 向量化

python - 对于列表中的每个点,计算到所有其他点的平均距离

python - sklearn线性回归中的参数copy_x是什么?

python - 划分数据框列: TypeError: 'int' object is not iterable

python - 将 2D 元素的大列表转换为 3D NumPy 数组 - 内存问题

python - scipy.special.erf 使用 0.j 引发运行时警告

python - scipy.signal.sepfir2d 中的类型错误