python - 将文本文件中的数字数组读入numpy数组 - python
问题描述
假设我有一个看起来像这样的文件
text a
bla bla
1 2 3
4 5 6
text b
bla
7 8 9
10 11 12
text c
bla bla bla
13 14 15
16 17 18
我试图只提取数字数组并将它们放入一个numpy
数组中:
array([[ 1, 2, 3,
4, 5, 6,],
[ 7, 8, 9,
10, 11, 12],
[ 13, 14, 15,
16, 17, 18]])
我尝试使用np.genfromtxt('test.txt',usecols=[0,1,2],invalid_raise=False)
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[ 10., 11., 12.],
[ nan, nan, nan],
[ 13., 14., 15.],
[ 16., 17., 18.]])
但它不会创建子数组并将文本转换为nans
. 有没有更好的方法来做到这一点?
解决方案
你可以itertools.groupby
使用
>>> import itertools
>>> import numpy as np
>>>
>>> content = """text a
...
... bla bla
...
... 1 2 3
... 4 5 6
...
... text b
...
... bla
...
... 7 8 9
... 10 11 12
...
... text c
...
... bla bla bla
...
... 13 14 15
... 16 17 18"""
>>>
>>> import io
>>> filelike = io.StringIO(content)
# you may want to refine this test
>>> allowed_characters = set('0123456789 ')
>>> def isnumeric(line):
... return set() < set(line.strip()) <= allowed_characters
...
>>> [np.genfromtxt(gr) for k, gr in itertools.groupby(filelike, isnumeric) if k]
[array([[1., 2., 3.],
[4., 5., 6.]]), array([[ 7., 8., 9.],
[10., 11., 12.]]), array([[13., 14., 15.],
[16., 17., 18.]])]
推荐阅读
- blazor - 从没有javascript的textarea中获取选定的文本
- java - 从字符串中删除相邻的重复项
- pyinstaller - pyinstaller 警告停止但可执行文件不起作用
- jquery - 使用 Jquery 抓取偶数/奇数、偶数/奇数、偶数/奇数对
- iis - 仅在使用 IIS ARR 代理时出现 HTTP 401 错误
- vb.net - 如何循环一个带有变量值的子?
- javascript - 在使用 node.js 时,我不断从具有 POST 请求方法的表单中获取 [object][Object] 作为我的请求
- ios - Swift FSCalendar 添加基于日期数组的事件
- directus - docker中的Directus 7添加用户
- c# - 使用结构和列表来存储部分 csv 文件