Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does numpy internally store size of an array?

Tags:

python

c

numpy

From specification of a numpy array at here:

typedef struct PyArrayObject {
    PyObject_HEAD
    char *data;
    int nd;
    npy_intp *dimensions;
    npy_intp *strides;
    PyObject *base;
    PyArray_Descr *descr;
    int flags;
    PyObject *weakreflist;
} PyArrayObject;

When I look at the specification of a numpy array, I don't see that it stores number of elements of the array. Is that really the case?

What is the advantage of not storing that?

Thank you.

like image 258
rxu Avatar asked Jan 19 '26 11:01

rxu


2 Answers

The size (that is, the total number of elements in the array) is computed as the product of the values in the array dimensions. The length of that array is nd.

In the C code that implements the core of numpy, you'll find many uses of the macro PyArray_SIZE(obj). Here's the definition of that macro:

#define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m))

The advantage of not storing it is, well, not storing redundant data.

like image 55
Warren Weckesser Avatar answered Jan 21 '26 23:01

Warren Weckesser


Look at PyArray_ArrayDescr *PyArray_Descr.subarray:

If this is non- NULL, then this data-type descriptor is a C-style contiguous array of another data-type descriptor. In other-words, each element that this descriptor describes is actually an array of some other base descriptor. This is most useful as the data-type descriptor for a field in another data-type descriptor. The fields member should be NULL if this is non- NULL (the fields member of the base descriptor can be non- NULL however). The PyArray_ArrayDescr structure is defined using

typedef struct {
    PyArray_Descr *base;
    PyObject *shape;      /* <-------- */
} PyArray_ArrayDescr;

and:

PyObject *PyArray_ArrayDescr.shape

The shape (always C-style contiguous) of the sub-array as a Python tuple.

like image 20
MaxU - stop WAR against UA Avatar answered Jan 22 '26 00:01

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!