Movatterモバイル変換


[0]ホーム

URL:


SciPy

The N-dimensional array (ndarray)

Anndarray is a (usually fixed-size) multidimensionalcontainer of items of the same type and size. The number of dimensionsand items in an array is defined by itsshape,which is atuple ofN positive integers that specify thesizes of each dimension. The type of items in the array is specified bya separatedata-type object (dtype), one of whichis associated with each ndarray.

As with other container objects in Python, the contents of anndarray can be accessed and modified byindexing orslicing the array (using, for example,N integers),and via the methods and attributes of thendarray.

Differentndarrays can share the same data, so thatchanges made in onendarray may be visible in another. Thatis, an ndarray can be a“view” to another ndarray, and the data itis referring to is taken care of by the“base” ndarray. ndarrays canalso be views to memory owned by Pythonstrings orobjects implementing thebuffer orarray interfaces.

Example

A 2-dimensional array of size 2 x 3, composed of 4-byte integerelements:

>>>x=np.array([[1,2,3],[4,5,6]],np.int32)>>>type(x)<type 'numpy.ndarray'>>>>x.shape(2, 3)>>>x.dtypedtype('int32')

The array can be indexed using Python container-like syntax:

>>># The element of x in the *second* row, *third* column, namely, 6.>>>x[1,2]

For exampleslicing can produce views ofthe array:

>>>y=x[:,1]>>>yarray([2, 5])>>>y[0]=9# this also changes the corresponding element in x>>>yarray([9, 5])>>>xarray([[1, 9, 3],       [4, 5, 6]])

Constructing arrays

New arrays can be constructed using the routines detailed inArray creation routines, and also by using the low-levelndarray constructor:

ndarray(shape[, dtype, buffer, offset, …])An array object represents a multidimensional, homogeneous array of fixed-size items.

Indexing arrays

Arrays can be indexed using an extended Python slicing syntax,array[selection]. Similar syntax is also used for accessingfields in astructured array.

Internal memory layout of an ndarray

An instance of classndarray consists of a contiguousone-dimensional segment of computer memory (owned by the array, or bysome other object), combined with an indexing scheme that mapsNintegers into the location of an item in the block. The ranges inwhich the indices can vary is specified by theshape of the array. How many bytes each item takes and howthe bytes are interpreted is defined by thedata-type object associated with the array.

A segment of memory is inherently 1-dimensional, and there are manydifferent schemes for arranging the items of anN-dimensional arrayin a 1-dimensional block. NumPy is flexible, andndarrayobjects can accommodate anystrided indexing scheme. In a stridedscheme, the N-dimensional index(n_0, n_1, ..., n_{N-1})corresponds to the offset (in bytes):

n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k

from the beginning of the memory block associated with thearray. Here,s_k are integers which specify thestrides of the array. Thecolumn-major order (used,for example, in the Fortran language and inMatlab) androw-major order (used in C) schemes are just specific kinds ofstrided scheme, and correspond to memory that can beaddressed by the strides:

s_k^{\mathrm{column}} = \mathrm{itemsize} \prod_{j=0}^{k-1} d_j ,\quad s_k^{\mathrm{row}} = \mathrm{itemsize} \prod_{j=k+1}^{N-1} d_j .

whered_j= self.shape[j].

Both the C and Fortran orders arecontiguous,i.e.,single-segment, memory layouts, in which every part of thememory block can be accessed by some combination of the indices.

While a C-style and Fortran-style contiguous array, which has the correspondingflags set, can be addressed with the above strides, the actual strides may bedifferent. This can happen in two cases:

  1. Ifself.shape[k]==1 then for any legal indexindex[k]==0.This means that in the formula for the offsetn_k = 0 and thuss_k n_k = 0 and the value ofs_k= self.strides[k] isarbitrary.
  2. If an array has no elements (self.size==0) there is no legalindex and the strides are never used. Any array with no elements may beconsidered C-style and Fortran-style contiguous.

Point 1. means thatself andself.squeeze() always have the samecontiguity andaligned flags value. This also means that even a highdimensional array could be C-style and Fortran-style contiguous at the sametime.

An array is considered aligned if the memory offsets for all elements and thebase offset itself is a multiple ofself.itemsize.

Note

Points (1) and (2) are not yet applied by default. Beginning withNumPy 1.8.0, they are applied consistently only if the environmentvariableNPY_RELAXED_STRIDES_CHECKING=1 was defined when NumPywas built. Eventually this will become the default.

You can check whether this option was enabled when your NumPy wasbuilt by looking at the value ofnp.ones((10,1),order='C').flags.f_contiguous. If this isTrue, then yourNumPy has relaxed strides checking enabled.

Warning

It doesnot generally hold thatself.strides[-1]==self.itemsizefor C-style contiguous arrays orself.strides[0]==self.itemsize forFortran-style contiguous arrays is true.

Data in newndarrays is in therow-major(C) order, unless otherwise specified, but, for example,basicarray slicing often producesviewsin a different scheme.

Note

Several algorithms in NumPy work on arbitrarily strided arrays.However, some algorithms require single-segment arrays. When anirregularly strided array is passed in to such algorithms, a copyis automatically made.

Array attributes

Array attributes reflect information that is intrinsic to the arrayitself. Generally, accessing an array through its attributes allowsyou to get and sometimes set intrinsic properties of the array withoutcreating a new array. The exposed attributes are the core parts of anarray and only some of them can be reset meaningfully without creatinga new array. Information on each attribute is given below.

Memory layout

The following attributes contain information about the memory layoutof the array:

ndarray.flagsInformation about the memory layout of the array.
ndarray.shapeTuple of array dimensions.
ndarray.stridesTuple of bytes to step in each dimension when traversing an array.
ndarray.ndimNumber of array dimensions.
ndarray.dataPython buffer object pointing to the start of the array’s data.
ndarray.sizeNumber of elements in the array.
ndarray.itemsizeLength of one array element in bytes.
ndarray.nbytesTotal bytes consumed by the elements of the array.
ndarray.baseBase object if memory is from some other object.

Data type

The data type object associated with the array can be found in thedtype attribute:

ndarray.dtypeData-type of the array’s elements.

Other attributes

ndarray.TSame as self.transpose(), except that self is returned if self.ndim < 2.
ndarray.realThe real part of the array.
ndarray.imagThe imaginary part of the array.
ndarray.flatA 1-D iterator over the array.
ndarray.ctypesAn object to simplify the interaction of the array with the ctypes module.

Array interface

__array_interface__Python-side of the array interface
__array_struct__C-side of the array interface

ctypes foreign function interface

ndarray.ctypesAn object to simplify the interaction of the array with the ctypes module.

Array methods

Anndarray object has many methods which operate on or withthe array in some fashion, typically returning an array result. Thesemethods are briefly explained below. (Each method’s docstring has amore complete description.)

For the following methods there are also corresponding functions innumpy:all,any,argmax,argmin,argpartition,argsort,choose,clip,compress,copy,cumprod,cumsum,diagonal,imag,max,mean,min,nonzero,partition,prod,ptp,put,ravel,real,repeat,reshape,round,searchsorted,sort,squeeze,std,sum,swapaxes,take,trace,transpose,var.

Array conversion

ndarray.item(*args)Copy an element of an array to a standard Python scalar and return it.
ndarray.tolist()Return the array as a (possibly nested) list.
ndarray.itemset(*args)Insert scalar into an array (scalar is cast to array’s dtype, if possible)
ndarray.tostring([order])Construct Python bytes containing the raw data bytes in the array.
ndarray.tobytes([order])Construct Python bytes containing the raw data bytes in the array.
ndarray.tofile(fid[, sep, format])Write array to a file as text or binary (default).
ndarray.dump(file)Dump a pickle of the array to the specified file.
ndarray.dumps()Returns the pickle of the array as a string.
ndarray.astype(dtype[, order, casting, …])Copy of the array, cast to a specified type.
ndarray.byteswap([inplace])Swap the bytes of the array elements
ndarray.copy([order])Return a copy of the array.
ndarray.view([dtype, type])New view of array with the same data.
ndarray.getfield(dtype[, offset])Returns a field of the given array as a certain type.
ndarray.setflags([write, align, uic])Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
ndarray.fill(value)Fill the array with a scalar value.

Shape manipulation

For reshape, resize, and transpose, the single tuple argument may bereplaced withn integers which will be interpreted as an n-tuple.

ndarray.reshape(shape[, order])Returns an array containing the same data with a new shape.
ndarray.resize(new_shape[, refcheck])Change shape and size of array in-place.
ndarray.transpose(*axes)Returns a view of the array with axes transposed.
ndarray.swapaxes(axis1, axis2)Return a view of the array withaxis1 andaxis2 interchanged.
ndarray.flatten([order])Return a copy of the array collapsed into one dimension.
ndarray.ravel([order])Return a flattened array.
ndarray.squeeze([axis])Remove single-dimensional entries from the shape ofa.

Item selection and manipulation

For array methods that take anaxis keyword, it defaults toNone. If axis isNone, then the array is treated as a 1-Darray. Any other value foraxis represents the dimension along whichthe operation should proceed.

ndarray.take(indices[, axis, out, mode])Return an array formed from the elements ofa at the given indices.
ndarray.put(indices, values[, mode])Seta.flat[n]=values[n] for alln in indices.
ndarray.repeat(repeats[, axis])Repeat elements of an array.
ndarray.choose(choices[, out, mode])Use an index array to construct a new array from a set of choices.
ndarray.sort([axis, kind, order])Sort an array, in-place.
ndarray.argsort([axis, kind, order])Returns the indices that would sort this array.
ndarray.partition(kth[, axis, kind, order])Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
ndarray.argpartition(kth[, axis, kind, order])Returns the indices that would partition this array.
ndarray.searchsorted(v[, side, sorter])Find indices where elements of v should be inserted in a to maintain order.
ndarray.nonzero()Return the indices of the elements that are non-zero.
ndarray.compress(condition[, axis, out])Return selected slices of this array along given axis.
ndarray.diagonal([offset, axis1, axis2])Return specified diagonals.

Calculation

Many of these methods take an argument namedaxis. In such cases,

  • Ifaxis isNone (the default), the array is treated as a 1-Darray and the operation is performed over the entire array. Thisbehavior is also the default if self is a 0-dimensional array orarray scalar. (An array scalar is an instance of the types/classesfloat32, float64, etc., whereas a 0-dimensional array is an ndarrayinstance containing precisely one array scalar.)
  • Ifaxis is an integer, then the operation is done over the givenaxis (for each 1-D subarray that can be created along the given axis).

Example of theaxis argument

A 3-dimensional array of size 3 x 3 x 3, summed over each of itsthree axes

>>>xarray([[[ 0,  1,  2],        [ 3,  4,  5],        [ 6,  7,  8]],       [[ 9, 10, 11],        [12, 13, 14],        [15, 16, 17]],       [[18, 19, 20],        [21, 22, 23],        [24, 25, 26]]])>>>x.sum(axis=0)array([[27, 30, 33],       [36, 39, 42],       [45, 48, 51]])>>># for sum, axis is the first keyword, so we may omit it,>>># specifying only its value>>>x.sum(0),x.sum(1),x.sum(2)(array([[27, 30, 33],        [36, 39, 42],        [45, 48, 51]]), array([[ 9, 12, 15],        [36, 39, 42],        [63, 66, 69]]), array([[ 3, 12, 21],        [30, 39, 48],        [57, 66, 75]]))

The parameterdtype specifies the data type over which a reductionoperation (like summing) should take place. The default reduce datatype is the same as the data type ofself. To avoid overflow, it canbe useful to perform the reduction using a larger data type.

For several methods, an optionalout argument can also be providedand the result will be placed into the output array given. Theoutargument must be anndarray and have the same number ofelements. It can have a different data type in which case casting willbe performed.

ndarray.argmax([axis, out])Return indices of the maximum values along the given axis.
ndarray.min([axis, out, keepdims])Return the minimum along a given axis.
ndarray.argmin([axis, out])Return indices of the minimum values along the given axis ofa.
ndarray.ptp([axis, out, keepdims])Peak to peak (maximum - minimum) value along a given axis.
ndarray.clip([min, max, out])Return an array whose values are limited to[min,max].
ndarray.conj()Complex-conjugate all elements.
ndarray.round([decimals, out])Returna with each element rounded to the given number of decimals.
ndarray.trace([offset, axis1, axis2, dtype, out])Return the sum along diagonals of the array.
ndarray.sum([axis, dtype, out, keepdims])Return the sum of the array elements over the given axis.
ndarray.cumsum([axis, dtype, out])Return the cumulative sum of the elements along the given axis.
ndarray.mean([axis, dtype, out, keepdims])Returns the average of the array elements along given axis.
ndarray.var([axis, dtype, out, ddof, keepdims])Returns the variance of the array elements, along given axis.
ndarray.std([axis, dtype, out, ddof, keepdims])Returns the standard deviation of the array elements along given axis.
ndarray.prod([axis, dtype, out, keepdims])Return the product of the array elements over the given axis
ndarray.cumprod([axis, dtype, out])Return the cumulative product of the elements along the given axis.
ndarray.all([axis, out, keepdims])Returns True if all elements evaluate to True.
ndarray.any([axis, out, keepdims])Returns True if any of the elements ofa evaluate to True.

Arithmetic, matrix multiplication, and comparison operations

Arithmetic and comparison operations onndarraysare defined as element-wise operations, and generally yieldndarray objects as results.

Each of the arithmetic operations (+,-,*,/,//,%,divmod(),** orpow(),<<,>>,&,^,|,~) and the comparisons (==,<,>,<=,>=,!=) is equivalent to the correspondinguniversal function (orufunc for short) in NumPy. Formore information, see the section onUniversal Functions.

Comparison operators:

ndarray.__lt__($self, value, /)Return self<value.
ndarray.__le__($self, value, /)Return self<=value.
ndarray.__gt__($self, value, /)Return self>value.
ndarray.__ge__($self, value, /)Return self>=value.
ndarray.__eq__($self, value, /)Return self==value.
ndarray.__ne__($self, value, /)Return self!=value.

Truth value of an array (bool):

ndarray.__nonzero__

Note

Truth-value testing of an array invokesndarray.__nonzero__, which raises an error if the number ofelements in the array is larger than 1, because the truth valueof such arrays is ambiguous. Use.any() and.all() instead to be clear about what is meantin such cases. (If the number of elements is 0, the array evaluatestoFalse.)

Unary operations:

ndarray.__neg__($self, /)-self
ndarray.__pos__($self, /)+self
ndarray.__abs__(self)
ndarray.__invert__($self, /)~self

Arithmetic:

ndarray.__add__($self, value, /)Return self+value.
ndarray.__sub__($self, value, /)Return self-value.
ndarray.__mul__($self, value, /)Return self*value.
ndarray.__div__
ndarray.__truediv__($self, value, /)Return self/value.
ndarray.__floordiv__($self, value, /)Return self//value.
ndarray.__mod__($self, value, /)Return self%value.
ndarray.__divmod__($self, value, /)Return divmod(self, value).
ndarray.__pow__($self, value[, mod])Return pow(self, value, mod).
ndarray.__lshift__($self, value, /)Return self<<value.
ndarray.__rshift__($self, value, /)Return self>>value.
ndarray.__and__($self, value, /)Return self&value.
ndarray.__or__($self, value, /)Return self|value.
ndarray.__xor__($self, value, /)Return self^value.

Note

  • Any third argument topow is silently ignored,as the underlyingufunc takes only two arguments.
  • The three division operators are all defined;div is activeby default,truediv is active when__future__ division is in effect.
  • Becausendarray is a built-in type (written in C), the__r{op}__ special methods are not directly defined.
  • The functions called to implement many arithmetic special methodsfor arrays can be modified usingset_numeric_ops.

Arithmetic, in-place:

ndarray.__iadd__($self, value, /)Return self+=value.
ndarray.__isub__($self, value, /)Return self-=value.
ndarray.__imul__($self, value, /)Return self*=value.
ndarray.__idiv__
ndarray.__itruediv__($self, value, /)Return self/=value.
ndarray.__ifloordiv__($self, value, /)Return self//=value.
ndarray.__imod__($self, value, /)Return self%=value.
ndarray.__ipow__($self, value, /)Return self**=value.
ndarray.__ilshift__($self, value, /)Return self<<=value.
ndarray.__irshift__($self, value, /)Return self>>=value.
ndarray.__iand__($self, value, /)Return self&=value.
ndarray.__ior__($self, value, /)Return self|=value.
ndarray.__ixor__($self, value, /)Return self^=value.

Warning

In place operations will perform the calculation using theprecision decided by the data type of the two operands, but willsilently downcast the result (if necessary) so it can fit back intothe array. Therefore, for mixed precision calculations,A{op}=B can be different thanA=A{op}B. For example, supposea=ones((3,3)). Then,a+=3j is different thana=a+3j: while they both perform the same computation,a+=3casts the result to fit back ina, whereasa=a+3jre-binds the namea to the result.

Matrix Multiplication:

ndarray.__matmul__($self, value, /)Returnself@value.

Note

Matrix operators@ and@= were introduced in Python 3.5following PEP465. NumPy 1.10.0 has a preliminary implementation of@for testing purposes. Further documentation can be found in thematmul documentation.

Special methods

For standard library functions:

ndarray.__copy__()Used ifcopy.copy is called on an array.
ndarray.__deepcopy__((memo, …)Used ifcopy.deepcopy is called on an array.
ndarray.__reduce__()For pickling.
ndarray.__setstate__(state, /)For unpickling.

Basic customization:

ndarray.__new__($type, *args, **kwargs)Create and return a new object.
ndarray.__array__(…)Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array.
ndarray.__array_wrap__(…)

Container customization: (seeIndexing)

ndarray.__len__($self, /)Return len(self).
ndarray.__getitem__($self, key, /)Return self[key].
ndarray.__setitem__($self, key, value, /)Set self[key] to value.
ndarray.__contains__($self, key, /)Return key in self.

Conversion; the operationscomplex,int,long,float,oct, andhex. They work only on arrays that have one element in themand return the appropriate scalar.

ndarray.__int__(self)
ndarray.__long__
ndarray.__float__(self)
ndarray.__oct__
ndarray.__hex__

String representations:

ndarray.__str__($self, /)Return str(self).
ndarray.__repr__($self, /)Return repr(self).

Table Of Contents

Previous topic

Array objects

Next topic

numpy.ndarray

Quick search

  • © Copyright 2008-2018, The SciPy community.
  • Last updated on Jul 24, 2018.
  • Created usingSphinx 1.6.6.

[8]ページ先頭

©2009-2025 Movatter.jp