我有一个如下所示的文件:
1 2 3 4 5 6 7
1 0 1 1 1 1 1 1
2 0 0 1 1 1 1 1
3 0 0 0 1 1 1 1
4 0 0 0 0 1 1 1
5 0 0 0 0 0 1 1
6 0 0 0 0 0 0 1
7 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
我只想读入 1 和 0 并忽略顶部标题行和行名称(第一列)。
到目前为止,我已经设置了标题行,但如何跳过跳过列。到目前为止我的代码
with open('file') as f:
next(f) #skips header row
content = [x.strip('\n') for x in f.readlines()]
Run Code Online (Sandbox Code Playgroud)
我试图只使用基本Python而不使用库。
使用简单的索引:
with open('file') as f:
next(f)
content = [x.strip().split()[1:] for x in f]
Run Code Online (Sandbox Code Playgroud)
这将为您提供分割的零和一作为嵌套列表。
如果您不想分割行,您仍然可以使用索引来删除第一个字符。
content = [x[1:].strip() for x in f]
Run Code Online (Sandbox Code Playgroud)
或者作为 Numpythonic 方法,您可以使用 Numpy 的loadtxt()函数:
>>> import numpy as np
>>> from io import StringIO
>>> np.loadtxt(StringIO(my_string), skiprows=1)[:,1:]
array([[ 0., 1., 1., 1., 1., 1., 1.],
[ 0., 0., 1., 1., 1., 1., 1.],
[ 0., 0., 0., 1., 1., 1., 1.],
[ 0., 0., 0., 0., 1., 1., 1.],
[ 0., 0., 0., 0., 0., 1., 1.],
[ 0., 0., 0., 0., 0., 0., 1.],
[ 0., 0., 0., 0., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6139 次 |
| 最近记录: |