Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.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 将文本文件转换为数组_Python_Arrays_Numpy - Fatal编程技术网

Python 将文本文件转换为数组

Python 将文本文件转换为数组,python,arrays,numpy,Python,Arrays,Numpy,python新手。我有一个文本文件,看起来像这样: 1 4 -69 -64 1 5 -57 -56 1 6 -59 -56 1 7 -69 -61 1 8 -53 -53 1 9 -69 -62 1 10 -65 -58 1 11 -69 -58 [[ 1 4 -69 -64 ] [ 1 5 -57 -56 ] [ 1 6 -59 -56 ] [ 1 7 -69 -61 ] [

python新手。我有一个文本文件,看起来像这样:

1   
4 
-69 
-64  
1   
5 
-57 
-56   
1   
6 
-59 
-56   
1   
7 
-69 
-61   
1   
8
-53 
-53   
1   
9 
-69 
-62   
1  
10 
-65 
-58   
1  
11 
-69 
-58
[[ 1 4 -69 -64 ]
[ 1 5 -57 -56 ]
[ 1 6 -59 -56 ] 
[ 1 7 -69 -61 ] 
[ 1 8 -53 -53 ] 
[ 1 9 -69 -62 ] 
[ 1 10 -65 -58 ]  
[ 1 11 -69 -58 ]]
要使用numpy将其转换为数组,该数组显示如下输出:

1   
4 
-69 
-64  
1   
5 
-57 
-56   
1   
6 
-59 
-56   
1   
7 
-69 
-61   
1   
8
-53 
-53   
1   
9 
-69 
-62   
1  
10 
-65 
-58   
1  
11 
-69 
-58
[[ 1 4 -69 -64 ]
[ 1 5 -57 -56 ]
[ 1 6 -59 -56 ] 
[ 1 7 -69 -61 ] 
[ 1 8 -53 -53 ] 
[ 1 9 -69 -62 ] 
[ 1 10 -65 -58 ]  
[ 1 11 -69 -58 ]]
尝试使用numpy.array,但无法获得所需的输出

希望这有点道理:)


非常感谢!非常感谢您的帮助

使用
np.genfromtxt
split

In [5]: arr = np.genfromtxt('test.txt')

In [6]: np.array(np.split(arr, arr.size/4))
Out[6]: 
array([[  1.,   4., -69., -64.],
       [  1.,   5., -57., -56.],
       [  1.,   6., -59., -56.],
       [  1.,   7., -69., -61.],
       [  1.,   8., -53., -53.],
       [  1.,   9., -69., -62.],
       [  1.,  10., -65., -58.],
       [  1.,  11., -69., -58.]])
或者首先使用
重塑()

In [14]: arr.reshape(arr.size//4, 4)
Out[14]: 
array([[  1.,   4., -69., -64.],
       [  1.,   5., -57., -56.],
       [  1.,   6., -59., -56.],
       [  1.,   7., -69., -61.],
       [  1.,   8., -53., -53.],
       [  1.,   9., -69., -62.],
       [  1.,  10., -65., -58.],
       [  1.,  11., -69., -58.]])

np.genfromtxt
+
。重塑
是一种方法:

import numpy as np

arr = np.genfromtxt('txt.csv')

arr.reshape((len(arr)/4, 4))

# array([[  1.,   4., -69., -64.],
#        [  1.,   5., -57., -56.],
#        [  1.,   6., -59., -56.],
#        [  1.,   7., -69., -61.],
#        [  1.,   8., -53., -53.],
#        [  1.,   9., -69., -62.],
#        [  1.,  10., -65., -58.],
#        [  1.,  11., -69., -58.]])

如果您已经使用您提到的
numpy.array
创建了一个数组,比如在一个名为
nums
的变量中,那么您可以执行以下操作:

nums = nums.reshape(-1, 4)

你到底试了什么?您得到了什么输出?尝试使用numpy.loadtxt,通过它我可以获取值。得到的输出是一个完整的数组,而不是所需的数组。这正是我想要的!非常感谢@如果这个答案回答了你的问题,你可以把它看作是帮助别人的答案,看看将来你会更喜欢Kasramvd这个问题。