![](/img/trans.png)
[英]How to extract multiple columns from a space delimited .DAT file in python
[英]Python read arrays delimited by white space from columns in a file
我有一个具有以下结构的文件:
1
2
3
23
33
55
1
2
4
...
等等。 所以我想将数据提取到多维数组,即[[1,2,3], [23,33,55], [1,2,4]...]
。 到目前为止,我已经尝试使用numpy.loadtxt()
函数,但是我得到了包含所有数字的一维数组,并且还尝试了以下代码段:
data_tot = []
with open('file.txt', 'r') as infile:
for line in infile:
if line.rstrip() != '':
data = []
data.append(line.rstrip())
else:
data_tot.append(data)
其中data_tot是我想要的数组,但是我得到了类似data_tot = [[1], [23], [1] ...]
关于如何解决此问题的任何想法。 提前致谢。
在您提供的代码段中,每当行不为空时,都会清除data
列表。
data_buf = []
data_tot = []
with open('file.txt', 'r') as infile:
for line in infile:
if line.rstrip() == '':
data_tot.append(data_buf[:])
data_buf = []
else:
data_buf.append(line.rstrip())
if len(data_buf) > 0:
data_tot.append(data_buf[:])
请注意,data_buf [:]复制列表对象以避免在下一次迭代中对其进行修改。 另外,如果最后一个缓冲区后面没有空行,则应将其添加到总列表中。
这是带有StringIO而不是文件的完整的独立示例代码
import io
f = io.StringIO("""1
2
3
23
33
55
1
2
4
""")
data_buf = []
data_tot = []
with f as infile:
for line in infile:
if line.rstrip() == '':
data_tot.append(data_buf[:])
data_buf = []
else:
data_buf.append(line.rstrip())
data_tot.append(data_buf[:])
您可以通过重塑来更改numpy数组的形状
#reshape the array to 3 by n
np.loadtxt("file.txt").reshape(-1,3)
随身携带的数据应该可以:
[[ 1. 2. 3.]
[ 23. 33. 55.]
[ 1. 2. 4.]
...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.