How can I import an array to python (numpy.arry) from a file and that way the file must be written if it doesn't already exist.
For example, save out a matrix to a file then load it back.
Python array module gives us an object type that we can use to denote an array. This is a collection of a type of values. In a way, this is like a Python list, but we specify a type at the time of creation. Here's a list of such type codes- Type Code.
It is useful when reading data from a file written on a machine with a different byte order. Return the number of occurrences of x in the array. Append items from iterable to the end of the array. If iterable is another array, it must have exactly the same type code; if not, TypeError will be raised.
Checkout the entry on the numpy example list. Here is the entry on .loadtxt()
>>> from numpy import *
>>>
>>> data = loadtxt("myfile.txt") # myfile.txt contains 4 columns of numbers
>>> t,z = data[:,0], data[:,3] # data is 2D numpy array
>>>
>>> t,x,y,z = loadtxt("myfile.txt", unpack=True) # to unpack all columns
>>> t,z = loadtxt("myfile.txt", usecols = (0,3), unpack=True) # to select just a few columns
>>> data = loadtxt("myfile.txt", skiprows = 7) # to skip 7 rows from top of file
>>> data = loadtxt("myfile.txt", comments = '!') # use '!' as comment char instead of '#'
>>> data = loadtxt("myfile.txt", delimiter=';') # use ';' as column separator instead of whitespace
>>> data = loadtxt("myfile.txt", dtype = int) # file contains integers instead of floats
Another option is numpy.genfromtxt
, e.g:
import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")
This will make data
a numpy array with as many rows and columns as are in your file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With