NumPy Application Notes: Basic Usage

I learn of NumPy while seeking one way to read a text file effectively. Therefore, I decide to put some notes here for convenient access.

1. Input and Output

1.1 Load data from a text file

np.loadtxt is used to load data from a simply formatted text file and return an array called ndarry.

import numpy as np

np.loadtxt(fname,                   # file or str, File, filename, or generator to read. 
            dtype=<type 'float'>,   # data-type, data-type of the resulting array; default: float.  
            comments='#',           # str or sequence, the characters or list of characters used to indicate the start of a comment.
            delimiter=None,         # str, by default, this is any whitespace.
            converters=None,        # dict, mapping column number to a function. E.g., if column 0 is a date string: converters = {0: datestr2num}.  
            skiprows=0,             # int, skip the first skiprows lines 
            usecols=None,           # sequence, identify which columns to read. E.g, `usecols = (1,4,5)` will extract the 2nd, 5th and 6th columns.
            unpack=False,           # If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...).
            ndmin=0)                # int, the returned array will have at least ndmin dimensions. The reLegal values: 0 (default), 1 or 2.

1.2 Save an array to a text file

np.savetxt is used to save an array to a text file.

np.savetxt(fname,           # filename or file handle, '.gz' is automatically saved in compressed gzip format. 
            X,              # array_like, data to be saved to a text file. 
            fmt='%.18e',    # str or sequence of strs, e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns (a list of specifiers, one per column) 
            delimiter=' ',  # str 
            newline='\n',   # str, string or character separating lines. 
            header='',      # str 
            footer='',      # str 
            comments='# ')  # str, string that will be prepended to the header and footer strings, to mark them as comments. 


电子邮件地址不会被公开。 必填项已用*标注