Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is numpy.ndarray.flags.contiguous about?

Tags:

python

numpy

While experimenting with Numpy, I found that the contiguous value provided by numpy.info may differ from numpy.ndarray.data.contiguous (see the code and screenshot below).

import numpy as np

x = np.arange(9).reshape(3,3)[:,(0,1)]

np.info(x)

print(f'''
{x.data.contiguous = }
{x.flags.contiguous = }

{x.data.c_contiguous = }
{x.flags.c_contiguous = }

{x.data.f_contiguous = }
{x.flags.f_contiguous = }
''')

According to documentation about a memoryview class, data.contiguous == True exactly if an array is either C-contiguous or Fortran contiguous. As for numpy.info, I believe it displays the value of flags.contiguous. Alas, there is no information about it in the manual. What does it actually mean? Is it a synonim for flags.c_contiguous?

experimental output

like image 727
Vitalizzare Avatar asked Oct 20 '25 17:10

Vitalizzare


1 Answers

In the source code of numpy.info, we can see the subroutine for processing ndarray:

def info(object=None, maxwidth=76, output=None, toplevel='numpy'):
    ...
    elif isinstance(object, ndarray):
        _info(object, output=output)
    ...

def _info(obj, output=None):
    """Provide information about ndarray obj"""
    bp = lambda x: x
    ...
    print("contiguous: ", bp(obj.flags.contiguous), file=output)
    print("fortran: ", obj.flags.fortran, file=output)
    ...

It returns flags.contiguous as the array's continuity parameter. This one isn't specified in flags description. But we can find it in flagsobject.c:

// ...
static PyGetSetDef arrayflags_getsets[] = {
    {"contiguous",
        (getter)arrayflags_contiguous_get,
        NULL,
        NULL, NULL},
    {"c_contiguous",
        (getter)arrayflags_contiguous_get,
        NULL,
        NULL, NULL},
// ...

So it's clear now that a contiguous parameter from numpy.info is actually flags.c_contiguous and has nothing in common with ndarray.data.contiguous. I guess when programming in C it was natural to say just contiguous instead of c_contiguous, and this has led to a slight inconsistency in terminology.

like image 161
Vitalizzare Avatar answered Oct 23 '25 06:10

Vitalizzare