Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy loadtxt后重塑:无法将大小为x的数组重塑为形状(x,y)_Python_File_Numpy - Fatal编程技术网

Python numpy loadtxt后重塑:无法将大小为x的数组重塑为形状(x,y)

Python numpy loadtxt后重塑:无法将大小为x的数组重塑为形状(x,y),python,file,numpy,Python,File,Numpy,我有以下文本文件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, delimi

我有以下文本文件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,但没有效果。

您不需要对数据进行
重塑
,只需将
loadtxt
函数中的分隔符从
更改为空格

data = np.loadtxt(file, delimiter=' ', dtype = str)
这实际上将以3x4字符串数组的形式加载数据,缺少的元素显示为空字符串
'
。然后可以使用

np.place(data, data == '', '0.0')
并使用以下命令转换为浮动:

data = np.asarray(data, dtype = float)

Pandas非常擅长读取缺少条目的数据。如果您没有熊猫,您可以使用以下设备安装:

pip install pandas
在此之后,您可以使用
pd.read\u table
读取数据。缺少的值将替换为
NaN
s

import pandas as pd
x = pd.read_table('data.txt', sep='\s+', 
            header=None, names=range(4)).values

print(x)
array([[    0.,     0.,     0.,    nan],
       [    0.,     0.,    10.,    nan],
       [   15.,    10.,  2001.,  2995.]])

不幸的是,这不是一个错误。我想这些只是空白。给我的文本文件在那里没有值。在我的示例中,我不确定如何正确地添加这些数据。那么您的数据是什么样子的呢?我的意思是,当我按照OP中的方式运行代码时,它给了我一个重塑错误,因为输入数组是一个3元素数组,每个元素都是示例输入的一行。是的,这一定是问题所在。很抱歉,我对这方面有点陌生。我们希望将该文本放入形状为3,4的numpy数组中。为什么对未由
分隔的文件使用
分隔符=','
?为什么断言输入结构为3x4?已修复分隔符。这就是我在文本编辑器中打开文件时的样子。在“复制粘贴”中,标签(如果有的话)不会通过。因此,您的示例看起来就像是用“空白”分隔的。前两行有3列,但最后一行有4列。因此出现了错误。