【问题标题】:Python reading a text file into a 2D array and accessing the dataPython 将文本文件读入二维数组并访问数据
【发布时间】:2018-12-19 15:17:10
【问题描述】:

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

这是数据的摘录,

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.

使用此处的示例,Import nastran nodes deck in Python using numpy

它可以导入,但它是一个一维数组,例如,我得到以下响应,

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 的经验,我在其中经常使用数组,但我很难理解如何加载数组以及如何访问特定数据。

【问题讨论】:

  • 检查shapedtype。不要假设文本是如何加载的。

标签: python python-3.x numpy multidimensional-array


【解决方案1】:

你可以使用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

【讨论】:

    【解决方案2】:

    您是从文本文件中导入它吗?你可以将文本文件保存为csv吗?如果是这样,您可以使用 pandas 轻松加载数据。

    import pandas as pd
    
    data = pd.read_csv(path_to_file)
    

    另外,您可能只需要使用以下方式重塑您的 numpy 数组:

    x = x.reshape(-1, 4)
    

    编辑: 由于您的格式基于固定宽度,因此您可能希望在 pandas 中使用固定宽度而不是 read_csv。下面的示例使用宽度为 8。

    x = pd.read_fwf(path_to_file, widths=8)
    

    【讨论】:

      猜你喜欢
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多