【发布时间】:2017-10-07 23:13:14
【问题描述】:
我有以下文本文件,file.txt 有 3 行 4 列:
0.0 0.0 0.0
0.0 0.0 10.0
15 10 2001 2995
我正在使用 np.loadtxt 将其作为数组读取。 Loadtxt 将其作为一维数组读入,我想将其转换回其结构与文本文件中相同的 3x4 数组。我试过了
file = sys.argv[1] #I'm just reading it from the command line when executing the program
data = np.loadtxt(file, delimiter='\t', dtype = str)
print(data.shape, data)
data = data.reshape(3,4)
但收到以下错误:
(3,)
['0.0 0.0 0.0' '0.0 0.0 10.0' '15 10 2001 2995']
ValueError: cannot reshape array of size 3 into shape (3,4)
我已经编辑掉了形状和错误之间的不相关信息。如何将此文本文件重新整形为 3x4 数组?它不必通过加载文本。我也尝试过使用 np.genfromtxt 也无济于事。
【问题讨论】:
-
你为什么要使用
delimiter=','来处理一个没有,分隔的文件? -
那你为什么断言输入结构是3x4?
-
修复了分隔符。这就是我在文本编辑器中打开文件时的样子。
-
在 `copy-n-paste 中,如果有标签,请不要通过。所以你的样本看起来就像'空白'分隔。前 2 行有 3 列,但最后有 4 列。因此出现错误。