简体   繁体   English

Numpy 将 txt 文件导入为没有文本行的矩阵

[英]Numpy import txt file as matrix without text lines

I have a txt file like the following, where I want to import the last column without the text so that I can do matrix vector operations with it我有一个如下所示的 txt 文件,我想在其中导入没有文本的最后一列,以便可以使用它进行矩阵向量运算

Node Number X Location (mm) Y Location (mm) Z Location (mm) Imported Initial Strain (mm/mm) 
1   54.545  29.798  7.3281  9.8534e-003 
2   53.976  28.979  7.2569  5.9253e-003 
3   68.579  16.26   7.3473  7.0993e-003 
4   67.902  16.955  7.3363  5.9801e-003 

I tried numpy.loadtxt("path")[1:,4] but get the following error which I assume is due to the text inside my txt file我试过numpy.loadtxt("path")[1:,4]但得到以下错误,我认为这是由于我的 txt 文件中的文本

ValueError: could not convert string to float: 'Node'

You might use numpy.genfromtext which allow ignoring starting line(s) with skip_header , so it your case:您可以使用numpy.genfromtext允许忽略带有skip_header的起始行,因此您的情况是:

import numpy as np
arr = np.genfromtxt("file.txt", skip_header=1)

should create numpy.ndarray from data from file.txt .应该从file.txt的数据创建numpy.ndarray Beware that in older versions of NumPy there is skiprows rather than skip_header in genfromtxt function (see linked docs for details).请注意,在旧版本的 NumPy 中, genfromtxt function 中有skiprows而不是skip_header (有关详细信息,请参阅链接文档)。

Numpy loadtxt has a number of parameters: Numpy loadtxt有多个参数:

  • skiprows allows to skip the initial rows skiprows 允许跳过初始行
  • usecols allows to only load a selection of columns usecols 只允许加载选择的列

Here what you want is:这里你想要的是:

arr = np.loadtxt(io.StringIO(t), skiprows=1, usecols=4)

With the sample data, it gives as expected:使用示例数据,它按预期给出:

array([0.0098534, 0.0059253, 0.0070993, 0.0059801])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM