Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import an array in python

Tags:

python

numpy

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.

like image 599
ricardo Avatar asked Nov 25 '09 12:11

ricardo


People also ask

What is import array in Python?

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.

Why do we need to import array in Python?

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.


2 Answers

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
like image 198
bayer Avatar answered Oct 03 '22 10:10

bayer


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

like image 38
atomh33ls Avatar answered Oct 03 '22 08:10

atomh33ls