简体   繁体   English

将文本文件转换为数组

[英]Convert Text file to Array

New to python.I have a text file which looks something like this: 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

Want to convert it to a array using numpy which shows output something like this: 想要使用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 ]]

Tried with numpy.array but could'nt get the desired output. 尝试使用numpy.array但无法获得所需的输出。

Hopefully, that makes some sense :) 希望这是有道理的:)

Thanks so much! 非常感谢! Any help is greatly appreciated! 任何帮助是极大的赞赏!

Use np.genfromtxt and split : 使用np.genfromtxtsplit

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.]])

Or just use reshape() at the first place: 或者只是在第一位置使用reshape()

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 + .reshape is one way: np.genfromtxt + .reshape是一种方法:

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)
>>> np.genfromtxt('so.txt').reshape(-1,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.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM