首页 > 解决方案 > Python 将文本文件读入二维数组并访问数据

问题描述

我正在尝试将文本文件中的数据读取到二维数组中,然后访问数据的每个元素。我尝试了许多不同的方法,但我无法访问数据的每个元素,

这是数据的摘录,

GRID     16             7.5     5.961539 0.
GRID     17             7.5     11.92308 0.
GRID     18             7.5     17.88461 0.
GRID     19             7.5     23.84615 0.
GRID     20             7.5     29.80769 0.
GRID     21             7.5     35.76923 0.
GRID     22             7.5     41.73077 0.
GRID     23             7.5     47.69231 0.
GRID     24             7.5     53.65384 0.

使用此处的示例,使用 numpy 在 Python 中导入 nastran 节点

它可以导入,但它作为一维数组和 I 'ary[1,1]' 例如,我得到以下响应,

x[1,1]
Traceback (most recent call last):

  File "<ipython-input-85-3e593ebbc211>", line 1, in <module>
    x[1,1]

IndexError: too many indices for array

我所希望的是,

17

我也尝试了以下代码,并再次将其读入一维数组,

ary = []

with open(os.path.join(dir, fn)) as fi:
    for line in fi:
        if line.startswith('GRID'):
            ary.append([line[i:i+8] for i in range(0, len(line), 8)])

我收到以下错误,

ary[1,2]
Traceback (most recent call last):

  File "<ipython-input-83-9ac21a0619e9>", line 1, in <module>
    ary[1,2]

TypeError: list indices must be integers or slices, not tuple

我是 Python 新手,但我确实有使用 VBA 的经验,我经常使用数组,但我很难理解如何加载数组以及如何访问特定数据。

标签: pythonpython-3.xnumpymultidimensional-array

解决方案


你可以使用genfromtxt函数。

import numpy as np

ary = np.genfromtxt(file_name, dtype=None)

这将自动加载您的文件并检测字段类型。现在您可以ary按行或按列访问,例如

In: ary['f1']
Out: array([16, 17, 18, 19, 20, 21, 22, 23, 24])

In: ary[2]
Out: (b'GRID', 18, 7.5, 17.88461, 0.)

或按单个元素:

In: ary[3]['f1']
Out: 19

In: ary['f1'][3]
Out: 19

推荐阅读