Skip to content
Advertisement

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

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

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

Advertisement

Answer

Numpy loadtxt has a number of parameters:

  • skiprows allows to skip the initial rows
  • usecols allows to only load a selection of columns

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])
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement