As the title says, I was trying to verify the ordering in numpy arrays by changing the ordering in the following test script:
import numpy as np
# Standard array
arr = [[1, 2, 3], [-7, -8, -9], ['A', 'B', 'C']]
print(arr, '\n')
for row_index, row_entries in enumerate(arr):
print('Row ' + str(row_index+1))
for column_index, column_entries in enumerate(row_entries):
print(' Column ' + str(column_index+1) + '\n', '\t [' + str(column_entries) + ']')
# NumPy array
arr = np.asarray([[1, 2, 3], [-7, -8, -9], ['A', 'B', 'C']], order='F') # Try 'C' vs. 'F'!!
print('\n\n', arr, '\n')
for row_index, row_entries in enumerate(arr):
print('Row ' + str(row_index+1))
for column_index, column_entries in enumerate(row_entries):
print(' Column ' + str(column_index+1) + '\n', '\t [' + str(column_entries) + ']')
----------------------------------------------------------------------------------------------
Output:
[[1, 2, 3], [-7, -8, -9], ['A', 'B', 'C']]
Row 1
Column 1
[1]
Column 2
[2]
Column 3
[3]
Row 2
Column 1
[-7]
Column 2
[-8]
Column 3
[-9]
Row 3
Column 1
[A]
Column 2
[B]
Column 3
[C]
[['1' '2' '3']
['-7' '-8' '-9']
['A' 'B' 'C']]
Row 1
Column 1
[1]
Column 2
[2]
Column 3
[3]
Row 2
Column 1
[-7]
Column 2
[-8]
Column 3
[-9]
Row 3
Column 1
[A]
Column 2
[B]
Column 3
[C]
Why am I getting identical outputs?
You start with a list (of lists):
Obviously we can iterate through the list, and through the sublists.
We can make an array from that list. Usually we don't specify the
order, but the default is 'C':Note that the dtype is strings (I suppose I could have specified
object).Same thing but with 'F':
Display is the same.
To see how the elements are stored we have to 'ravel' the arrays. The result is a new 1d array. See
np.reshapeornp.raveldocs for the use of 'K' order:Here we read the values of
arr2down the columns.ravelof the first array, but with 'F' order produces the same thing:Iteration as you do, doesn't change with the
order. It effectively treats the array as a list.You have to use
numpy'sown methods and tools to see the effect oforder.orderis more useful when creating an array viareshape:Tweaking the shape, and then applying a transpose:
edit
It may be clearer if I make a smaller array with just 1 byte per element.
The 2 orders:
Instead of
ravel, usetobyteswith 'A' order to preserve the underlying order (seetobytesdocs):The difference can alse be seen in the strides:
stridescontrols hownumpyiterates through the array in compiled code (but not when using python level iteration).A comment suggested using
nditerto iterate via numpy's own methods. Generally I don't recommend usingnditer, but here it is is illustrative:nditertakes anorder, but 'K' is default (in contrast to many other cases where 'C' is the default).