16

How can I find out if a n-dimensional numpy array Arr is contiguous in C-style or Fortran-style?

1
  • 1
    Also look at the strides. Commented Jul 12, 2018 at 15:11

2 Answers 2

25

The numpy documentation states that it is possible to check whether an array is C-contiguous or Fortran-contiguous via the attribute flags:

Arr.flags['C_CONTIGUOUS']
Arr.flags['F_CONTIGUOUS']

These attributes return a boolean indicating which of the two cases is true.

Sign up to request clarification or add additional context in comments.

5 Comments

Excepts it is not a function, it is actually an attribute of the numpy.ndarray object, as your reported syntax (which is correct) suggests.
@norok2, you are right! I edited the answer. Thanks!
And with some axis swapping it possible that neither will be True. And both are True for a 1d array
there is also numpy.ascontiguousarray which may sometimes be helpful.
"And both are True for a 1d array" -- not always. For example, np.zeros(30)[::3] has False for both flags.
14

You can also try the ndarray.data.contiguous member. E.g. (on my machine):

arr = np.arange(6).reshape(2, 3)

print(arr.data.contiguous)  # True
print(arr.data.c_contiguous)  # True
print(arr.data.f_contiguous)  # False

(I can't find any information re: which numpy versions support this, even on their docs. Any leads welcome in the comments!)

1 Comment

Note: this will not work with datetime64 arrays; you get ValueError: cannot include dtype 'M' in a buffer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.