python - 读取 txt 矩阵时,如何跳过第一列

标签 python

我有一个看起来像这样的文件:

    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

我只想读入 1 和 0 并忽略顶部标题行和行名(第一列)。

到目前为止,我已设置好标题行,但如何才能跳过跳过列。到目前为止我的代码

with open('file') as f:
    next(f) #skips header row
    content = [x.strip('\n') for x in f.readlines()]

我试图只使用基本 python 而没有库。

最佳答案

使用简单的索引:

with open('file') as f:
    next(f)
    content = [x.strip().split()[1:] for x in f]

这将为您提供拆分的零和一个作为嵌套列表。

如果您不想拆分行,您仍然可以使用索引来删除第一个字符。

content = [x[1:].strip() for x in f]

或者作为 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.]])

关于python - 读取 txt 矩阵时,如何跳过第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37393760/

相关文章:

python - 如何修复 : AttributeError: module 'tensorflow' has no attribute 'optimizers' in JupyterNotebook (using colab. 研究)

python - 提高二维 numpy 数组迭代性能

python - 使用 Fabric 将命令置于后台在某些主机上不起作用

python - 将列表转换为子列表,同时保留 "key"

python - URL 附加到 WSGI 脚本的路径,为什么?

python - 多处理 - 共享一个复杂的对象

python - Python 中字典值的稳定排序

python - pyodbc 导入错误 : DLL load failed: %1 is not a valid Win32 application

python - 从每组的另一列获取与 idxmax 对应的列值

python - 如何在 Windows 上捕获 PyCharm 中的停止按钮?