Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import .dat file in Python 3

Tags:

python

numpy

I would like to import a .dat file which includes

lines/header/numbers/lines 

something like this example

start using data to calculate something
 x y z g h 
 1 4 6 8 3
 4 5 6 8 9 
 2 3 6 8 5
end the data that I should import.

Now I am trying to read this file, remove first and last lines and put the numbers in an array and do some basic calculation on them, But I could not get rid of the lines. I used data = np.genfromtxt('sample.dat') to import data, but with lines, I cannot do anything. Can anyone help me?

like image 485
Faye Avatar asked Mar 09 '17 19:03

Faye


1 Answers

Maybe this helps you:

import numpy as np

data = np.genfromtxt('sample.dat',
                     skip_header=1,
                     skip_footer=1,
                     names=True,
                     dtype=None,
                     delimiter=' ')
print(data)
# Output: [(1, 4, 6, 8, 3) (4, 5, 6, 8, 9) (2, 3, 6, 8, 5)]

Please refer to the numpy documentation for further information about the parameters used: https://numpy.org/doc/stable/reference/generated/numpy.genfromtxt.html

like image 62
Roman Alexeev Avatar answered Sep 19 '22 16:09

Roman Alexeev